hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
8e4ded8d3d43d0e5fdddb7ac5940d962e174875c
mateusap1/athenas
model/identity.py
[ "MIT" ]
Python
is_valid
bool
def is_valid(self) -> bool: """Verfies if ID is valid or not""" if len(self.__username) > USERNAME_LIMIT: return False if self.__nonce > NONCE_LIMIT: return False content = { "username": self.__username, "public_key": self.__public_key, ...
Verfies if ID is valid or not
Verfies if ID is valid or not
[ "Verfies", "if", "ID", "is", "valid", "or", "not" ]
def is_valid(self) -> bool: if len(self.__username) > USERNAME_LIMIT: return False if self.__nonce > NONCE_LIMIT: return False content = { "username": self.__username, "public_key": self.__public_key, "nonce": self.__nonce, ...
[ "def", "is_valid", "(", "self", ")", "->", "bool", ":", "if", "len", "(", "self", ".", "__username", ")", ">", "USERNAME_LIMIT", ":", "return", "False", "if", "self", ".", "__nonce", ">", "NONCE_LIMIT", ":", "return", "False", "content", "=", "{", "\"u...
Verfies if ID is valid or not
[ "Verfies", "if", "ID", "is", "valid", "or", "not" ]
[ "\"\"\"Verfies if ID is valid or not\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8e4ded8d3d43d0e5fdddb7ac5940d962e174875c
mateusap1/athenas
model/identity.py
[ "MIT" ]
Python
is_id_valid
bool
def is_id_valid(userid: dict) -> bool: """Verfies if a dictionary version of an ID is valid or not""" required_keys = ["username", "public_key", "nonce", "timestamp", "hash_value"] if Counter(userid.keys()) != Counter(required_keys): # If, doesn't matter th...
Verfies if a dictionary version of an ID is valid or not
Verfies if a dictionary version of an ID is valid or not
[ "Verfies", "if", "a", "dictionary", "version", "of", "an", "ID", "is", "valid", "or", "not" ]
def is_id_valid(userid: dict) -> bool: required_keys = ["username", "public_key", "nonce", "timestamp", "hash_value"] if Counter(userid.keys()) != Counter(required_keys): return False expected_types = { "username": str, "public_key": s...
[ "def", "is_id_valid", "(", "userid", ":", "dict", ")", "->", "bool", ":", "required_keys", "=", "[", "\"username\"", ",", "\"public_key\"", ",", "\"nonce\"", ",", "\"timestamp\"", ",", "\"hash_value\"", "]", "if", "Counter", "(", "userid", ".", "keys", "(", ...
Verfies if a dictionary version of an ID is valid or not
[ "Verfies", "if", "a", "dictionary", "version", "of", "an", "ID", "is", "valid", "or", "not" ]
[ "\"\"\"Verfies if a dictionary version of an ID is valid or not\"\"\"", "# If, doesn't matter the order, the keys are not all", "# the same as the expected ones, return False", "# Returns false if any of the id values have a", "# different type other than the expected" ]
[ { "param": "userid", "type": "dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "userid", "type": "dict", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e98f6b24123e1da75fd1b0bad2fddf70057e8024
mateusap1/athenas
model/transaction/Accusation.py
[ "MIT" ]
Python
to_dict
dict
def to_dict(self) -> dict: """Returns 'Transaction' content on a dictionary format""" return { "sender": self.__sender.to_dict(), "accused": self.__accused.to_dict(), "contract": self.__contract.to_dict(), "signature": self.__signature }
Returns 'Transaction' content on a dictionary format
Returns 'Transaction' content on a dictionary format
[ "Returns", "'", "Transaction", "'", "content", "on", "a", "dictionary", "format" ]
def to_dict(self) -> dict: return { "sender": self.__sender.to_dict(), "accused": self.__accused.to_dict(), "contract": self.__contract.to_dict(), "signature": self.__signature }
[ "def", "to_dict", "(", "self", ")", "->", "dict", ":", "return", "{", "\"sender\"", ":", "self", ".", "__sender", ".", "to_dict", "(", ")", ",", "\"accused\"", ":", "self", ".", "__accused", ".", "to_dict", "(", ")", ",", "\"contract\"", ":", "self", ...
Returns 'Transaction' content on a dictionary format
[ "Returns", "'", "Transaction", "'", "content", "on", "a", "dictionary", "format" ]
[ "\"\"\"Returns 'Transaction' content on a dictionary format\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
df9c3837cc497dee185e19ea8e4b70853350c078
mateusap1/athenas
model/transaction/Verdict.py
[ "MIT" ]
Python
to_dict
dict
def to_dict(self) -> dict: """Returns 'Transaction' content on a dictionary format""" return { "sender": self.__sender.to_dict(), "accusation": self.__accusation.to_dict(), "sentence": self.__sentence, "description": self.__description, "signa...
Returns 'Transaction' content on a dictionary format
Returns 'Transaction' content on a dictionary format
[ "Returns", "'", "Transaction", "'", "content", "on", "a", "dictionary", "format" ]
def to_dict(self) -> dict: return { "sender": self.__sender.to_dict(), "accusation": self.__accusation.to_dict(), "sentence": self.__sentence, "description": self.__description, "signature": self.__signature }
[ "def", "to_dict", "(", "self", ")", "->", "dict", ":", "return", "{", "\"sender\"", ":", "self", ".", "__sender", ".", "to_dict", "(", ")", ",", "\"accusation\"", ":", "self", ".", "__accusation", ".", "to_dict", "(", ")", ",", "\"sentence\"", ":", "se...
Returns 'Transaction' content on a dictionary format
[ "Returns", "'", "Transaction", "'", "content", "on", "a", "dictionary", "format" ]
[ "\"\"\"Returns 'Transaction' content on a dictionary format\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ec9c4de1164a6b2e7c7e19b79e85fce4abedacbe
DaviAMSilva/Mosaico_de_Fotos
PhotoMosaic.py
[ "MIT" ]
Python
create_mosaic
bool
def create_mosaic( main_image_path:str, size:int, resolution:int, samples_path:str = ".\\", name:str = "Mosaic.jpg", recursive:bool = False, color_mode:str = "SIMPLIFIED", resize_mode:str = "BICUBIC", formats:list = [] ) -> bool: """ ### Creates a images mosaic combining many...
### Creates a images mosaic combining many sample images to \ create a bigger image that resembles the original main image #### Arguments: - main_image_path {str} -- Path to the main image, source to the mosaic image - size {int} -- Size of each tile in the main image (different from tile reso...
Creates a images mosaic combining many sample images to \ create a bigger image that resembles the original main image {bool} -- Whether or not the function exited successfully
[ "Creates", "a", "images", "mosaic", "combining", "many", "sample", "images", "to", "\\", "create", "a", "bigger", "image", "that", "resembles", "the", "original", "main", "image", "{", "bool", "}", "--", "Whether", "or", "not", "the", "function", "exited", ...
def create_mosaic( main_image_path:str, size:int, resolution:int, samples_path:str = ".\\", name:str = "Mosaic.jpg", recursive:bool = False, color_mode:str = "SIMPLIFIED", resize_mode:str = "BICUBIC", formats:list = [] ) -> bool: try: main_image:PIL.Image.Image = PIL.Imag...
[ "def", "create_mosaic", "(", "main_image_path", ":", "str", ",", "size", ":", "int", ",", "resolution", ":", "int", ",", "samples_path", ":", "str", "=", "\".\\\\\"", ",", "name", ":", "str", "=", "\"Mosaic.jpg\"", ",", "recursive", ":", "bool", "=", "Fa...
Creates a images mosaic combining many sample images to \ create a bigger image that resembles the original main image
[ "Creates", "a", "images", "mosaic", "combining", "many", "sample", "images", "to", "\\", "create", "a", "bigger", "image", "that", "resembles", "the", "original", "main", "image" ]
[ "\"\"\"\n ### Creates a images mosaic combining many sample images to \\\n create a bigger image that resembles the original main image\n \n #### Arguments:\n - main_image_path {str} -- Path to the main image, source to the mosaic image\n - size {int} -- Size of each tile in the main image (differ...
[ { "param": "main_image_path", "type": "str" }, { "param": "size", "type": "int" }, { "param": "resolution", "type": "int" }, { "param": "samples_path", "type": "str" }, { "param": "name", "type": "str" }, { "param": "recursive", "type": "bool" },...
{ "returns": [], "raises": [], "params": [ { "identifier": "main_image_path", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "size", "type": "int", "docstring": null, "docstri...
56cfeb08083154e4bfe66068b99fe3e4c0e292ae
mfkiwl/ORCs
ORC_R32IMAZicsr/sim/orc_r32i_predictor.py
[ "BSD-3-Clause" ]
Python
build_phase
null
def build_phase(self, phase): super().build_phase(phase) """ Function: build_phase Definition: Brings this agent's virtual interface. Args: phase: build_phase """ self.ap = UVMAnalysisPort("ap", self)
Function: build_phase Definition: Brings this agent's virtual interface. Args: phase: build_phase
build_phase Definition: Brings this agent's virtual interface.
[ "build_phase", "Definition", ":", "Brings", "this", "agent", "'", "s", "virtual", "interface", "." ]
def build_phase(self, phase): super().build_phase(phase) self.ap = UVMAnalysisPort("ap", self)
[ "def", "build_phase", "(", "self", ",", "phase", ")", ":", "super", "(", ")", ".", "build_phase", "(", "phase", ")", "self", ".", "ap", "=", "UVMAnalysisPort", "(", "\"ap\"", ",", "self", ")" ]
Function: build_phase Definition: Brings this agent's virtual interface.
[ "Function", ":", "build_phase", "Definition", ":", "Brings", "this", "agent", "'", "s", "virtual", "interface", "." ]
[ "\"\"\" \n Function: build_phase\n \n Definition: Brings this agent's virtual interface.\n\n Args:\n phase: build_phase\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "phase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "phase", "type": null, "docstring": null, "docstring_tokens": ...
56cfeb08083154e4bfe66068b99fe3e4c0e292ae
mfkiwl/ORCs
ORC_R32IMAZicsr/sim/orc_r32i_predictor.py
[ "BSD-3-Clause" ]
Python
create_response
null
def create_response(self, t): """ Function: create_response Definition: Creates a response transaction and updates the pc counter. Args: t: wb_master_seq (Sequence Item) """ tr = [] tr = t self.ap.write(tr)
Function: create_response Definition: Creates a response transaction and updates the pc counter. Args: t: wb_master_seq (Sequence Item)
create_response Definition: Creates a response transaction and updates the pc counter.
[ "create_response", "Definition", ":", "Creates", "a", "response", "transaction", "and", "updates", "the", "pc", "counter", "." ]
def create_response(self, t): tr = [] tr = t self.ap.write(tr)
[ "def", "create_response", "(", "self", ",", "t", ")", ":", "tr", "=", "[", "]", "tr", "=", "t", "self", ".", "ap", ".", "write", "(", "tr", ")" ]
Function: create_response Definition: Creates a response transaction and updates the pc counter.
[ "Function", ":", "create_response", "Definition", ":", "Creates", "a", "response", "transaction", "and", "updates", "the", "pc", "counter", "." ]
[ "\"\"\" \n Function: create_response\n \n Definition: Creates a response transaction and updates the pc counter. \n\n Args:\n t: wb_master_seq (Sequence Item)\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "t", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "t", "type": null, "docstring": "wb_master_seq (Sequence Item)", ...
6a9b276c7576c9fa9844b2647d18380711590a1f
mfkiwl/ORCs
ORC_R32IMAZicsr/sim/orc_r32i_tb_env.py
[ "BSD-3-Clause" ]
Python
build_phase
null
def build_phase(self, phase): super().build_phase(phase) """ Function: build_phase Definition: Gets configurations from the UVMDb and creates components. Args: phase: build_phase """ arr = [] if (not UVMConfigDb.g...
Function: build_phase Definition: Gets configurations from the UVMDb and creates components. Args: phase: build_phase
build_phase Definition: Gets configurations from the UVMDb and creates components.
[ "build_phase", "Definition", ":", "Gets", "configurations", "from", "the", "UVMDb", "and", "creates", "components", "." ]
def build_phase(self, phase): super().build_phase(phase) arr = [] if (not UVMConfigDb.get(self, "", "tb_env_config", arr)): uvm_fatal("ORC_R32I_TB_ENV/NoTbEnvConfig", "Test Bench config not found") self.cfg = arr[0] self.inst_agent = wb_master_agent.type_id.create("in...
[ "def", "build_phase", "(", "self", ",", "phase", ")", ":", "super", "(", ")", ".", "build_phase", "(", "phase", ")", "arr", "=", "[", "]", "if", "(", "not", "UVMConfigDb", ".", "get", "(", "self", ",", "\"\"", ",", "\"tb_env_config\"", ",", "arr", ...
Function: build_phase Definition: Gets configurations from the UVMDb and creates components.
[ "Function", ":", "build_phase", "Definition", ":", "Gets", "configurations", "from", "the", "UVMDb", "and", "creates", "components", "." ]
[ "\"\"\" \n Function: build_phase\n \n Definition: Gets configurations from the UVMDb and creates components.\n\n Args:\n phase: build_phase\n \"\"\"", "#self.predictor = UVMRegPredictor.type_id.create(\"predictor\", self)", "#self.scoreboard = sc...
[ { "param": "self", "type": null }, { "param": "phase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "phase", "type": null, "docstring": null, "docstring_tokens": ...
bcb64b00259a23392ff500180d2c51631187e267
arXiv/arxiv-fulltext
fulltext/domain.py
[ "MIT" ]
Python
to_dict
dict
def to_dict(self) -> dict: """Generate a dict representation of this placeholder.""" return { 'identifier': self.identifier, 'version': self.version, 'started': self.started.isoformat() if self.started else None, 'ended': self.ended.isoformat() if self.end...
Generate a dict representation of this placeholder.
Generate a dict representation of this placeholder.
[ "Generate", "a", "dict", "representation", "of", "this", "placeholder", "." ]
def to_dict(self) -> dict: return { 'identifier': self.identifier, 'version': self.version, 'started': self.started.isoformat() if self.started else None, 'ended': self.ended.isoformat() if self.ended else None, 'owner': self.owner, 'task_i...
[ "def", "to_dict", "(", "self", ")", "->", "dict", ":", "return", "{", "'identifier'", ":", "self", ".", "identifier", ",", "'version'", ":", "self", ".", "version", ",", "'started'", ":", "self", ".", "started", ".", "isoformat", "(", ")", "if", "self"...
Generate a dict representation of this placeholder.
[ "Generate", "a", "dict", "representation", "of", "this", "placeholder", "." ]
[ "\"\"\"Generate a dict representation of this placeholder.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
28809ee0aff8cd3aecb71d10dad444010cfb81e8
arXiv/arxiv-fulltext
fulltext/services/util.py
[ "MIT" ]
Python
read
bytes
def read(self, *args: Any, **kwargs: Any) -> bytes: """ Read the next chunk of the content stream. Arguments are ignored, since the chunk size must be set at the start. """ return next(self._iter_content, b'')
Read the next chunk of the content stream. Arguments are ignored, since the chunk size must be set at the start.
Read the next chunk of the content stream. Arguments are ignored, since the chunk size must be set at the start.
[ "Read", "the", "next", "chunk", "of", "the", "content", "stream", ".", "Arguments", "are", "ignored", "since", "the", "chunk", "size", "must", "be", "set", "at", "the", "start", "." ]
def read(self, *args: Any, **kwargs: Any) -> bytes: return next(self._iter_content, b'')
[ "def", "read", "(", "self", ",", "*", "args", ":", "Any", ",", "**", "kwargs", ":", "Any", ")", "->", "bytes", ":", "return", "next", "(", "self", ".", "_iter_content", ",", "b''", ")" ]
Read the next chunk of the content stream.
[ "Read", "the", "next", "chunk", "of", "the", "content", "stream", "." ]
[ "\"\"\"\n Read the next chunk of the content stream.\n\n Arguments are ignored, since the chunk size must be set at the start.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "args", "type": "Any" }, { "param": "kwargs", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "args", "type": "Any", "docstring": null, "docstring_tokens": ...
88b21a91455f3c39c244d7c674a7c741216d0b6f
arXiv/arxiv-fulltext
fulltext/services/preview/tests.py
[ "MIT" ]
Python
tearDownClass
null
def tearDownClass(cls): """Tear down the preview service and localstack.""" cls.container.kill() cls.container.remove() cls.localstack.kill() cls.localstack.remove() cls.network.remove()
Tear down the preview service and localstack.
Tear down the preview service and localstack.
[ "Tear", "down", "the", "preview", "service", "and", "localstack", "." ]
def tearDownClass(cls): cls.container.kill() cls.container.remove() cls.localstack.kill() cls.localstack.remove() cls.network.remove()
[ "def", "tearDownClass", "(", "cls", ")", ":", "cls", ".", "container", ".", "kill", "(", ")", "cls", ".", "container", ".", "remove", "(", ")", "cls", ".", "localstack", ".", "kill", "(", ")", "cls", ".", "localstack", ".", "remove", "(", ")", "cls...
Tear down the preview service and localstack.
[ "Tear", "down", "the", "preview", "service", "and", "localstack", "." ]
[ "\"\"\"Tear down the preview service and localstack.\"\"\"" ]
[ { "param": "cls", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
082d3ee445ce1040c0e1899c2eaeaee1cd921757
arXiv/arxiv-fulltext
fulltext/factory.py
[ "MIT" ]
Python
create_web_app
Flask
def create_web_app(for_worker: bool = False) -> Flask: """Initialize an instance of the web application.""" app = Flask('fulltext') app.config.from_pyfile('config.py') app.url_map.converters['source'] = SubmissionSourceConverter if app.config['LOGLEVEL'] < 40: # Make sure that boto doesn't ...
Initialize an instance of the web application.
Initialize an instance of the web application.
[ "Initialize", "an", "instance", "of", "the", "web", "application", "." ]
def create_web_app(for_worker: bool = False) -> Flask: app = Flask('fulltext') app.config.from_pyfile('config.py') app.url_map.converters['source'] = SubmissionSourceConverter if app.config['LOGLEVEL'] < 40: pylogging.getLogger('boto').setLevel(pylogging.ERROR) pylogging.getLogger('boto3...
[ "def", "create_web_app", "(", "for_worker", ":", "bool", "=", "False", ")", "->", "Flask", ":", "app", "=", "Flask", "(", "'fulltext'", ")", "app", ".", "config", ".", "from_pyfile", "(", "'config.py'", ")", "app", ".", "url_map", ".", "converters", "[",...
Initialize an instance of the web application.
[ "Initialize", "an", "instance", "of", "the", "web", "application", "." ]
[ "\"\"\"Initialize an instance of the web application.\"\"\"", "# Make sure that boto doesn't spam the logs when we're in debug mode.", "# type: ignore" ]
[ { "param": "for_worker", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "for_worker", "type": "bool", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
082d3ee445ce1040c0e1899c2eaeaee1cd921757
arXiv/arxiv-fulltext
fulltext/factory.py
[ "MIT" ]
Python
wait_for
None
def wait_for(service: IAwaitable, delay: int = 2, **extra: Any) -> None: """Wait for a service to become available.""" if hasattr(service, '__name__'): service_name = service.__name__ # type: ignore elif hasattr(service, '__class__'): service_name = service.__class__.__name__ else: ...
Wait for a service to become available.
Wait for a service to become available.
[ "Wait", "for", "a", "service", "to", "become", "available", "." ]
def wait_for(service: IAwaitable, delay: int = 2, **extra: Any) -> None: if hasattr(service, '__name__'): service_name = service.__name__ elif hasattr(service, '__class__'): service_name = service.__class__.__name__ else: service_name = str(service) logger.info('await %s', se...
[ "def", "wait_for", "(", "service", ":", "IAwaitable", ",", "delay", ":", "int", "=", "2", ",", "**", "extra", ":", "Any", ")", "->", "None", ":", "if", "hasattr", "(", "service", ",", "'__name__'", ")", ":", "service_name", "=", "service", ".", "__na...
Wait for a service to become available.
[ "Wait", "for", "a", "service", "to", "become", "available", "." ]
[ "\"\"\"Wait for a service to become available.\"\"\"", "# type: ignore" ]
[ { "param": "service", "type": "IAwaitable" }, { "param": "delay", "type": "int" }, { "param": "extra", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "service", "type": "IAwaitable", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "delay", "type": "int", "docstring": null, "docstri...
d850a48868059577ef48f516a0a88dffa8f864d3
arXiv/arxiv-fulltext
fulltext/routes.py
[ "MIT" ]
Python
make_authorizer
Authorizer
def make_authorizer(scope: Scope) -> Authorizer: """Make an authorizer function for injection into a controller.""" def inner(identifier: str, owner_id: Optional[str]) -> bool: """Check whether the session is authorized for a specific resource.""" logger.debug('Authorize for %s owned by %s', ide...
Make an authorizer function for injection into a controller.
Make an authorizer function for injection into a controller.
[ "Make", "an", "authorizer", "function", "for", "injection", "into", "a", "controller", "." ]
def make_authorizer(scope: Scope) -> Authorizer: def inner(identifier: str, owner_id: Optional[str]) -> bool: logger.debug('Authorize for %s owned by %s', identifier, owner_id) logger.debug('Client user id is %s', request.auth.user.user_id) try: source_id, checksum = identifier.s...
[ "def", "make_authorizer", "(", "scope", ":", "Scope", ")", "->", "Authorizer", ":", "def", "inner", "(", "identifier", ":", "str", ",", "owner_id", ":", "Optional", "[", "str", "]", ")", "->", "bool", ":", "\"\"\"Check whether the session is authorized for a spe...
Make an authorizer function for injection into a controller.
[ "Make", "an", "authorizer", "function", "for", "injection", "into", "a", "controller", "." ]
[ "\"\"\"Make an authorizer function for injection into a controller.\"\"\"", "\"\"\"Check whether the session is authorized for a specific resource.\"\"\"" ]
[ { "param": "scope", "type": "Scope" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "scope", "type": "Scope", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
d850a48868059577ef48f516a0a88dffa8f864d3
arXiv/arxiv-fulltext
fulltext/routes.py
[ "MIT" ]
Python
inner
bool
def inner(identifier: str, owner_id: Optional[str]) -> bool: """Check whether the session is authorized for a specific resource.""" logger.debug('Authorize for %s owned by %s', identifier, owner_id) logger.debug('Client user id is %s', request.auth.user.user_id) try: source_i...
Check whether the session is authorized for a specific resource.
Check whether the session is authorized for a specific resource.
[ "Check", "whether", "the", "session", "is", "authorized", "for", "a", "specific", "resource", "." ]
def inner(identifier: str, owner_id: Optional[str]) -> bool: logger.debug('Authorize for %s owned by %s', identifier, owner_id) logger.debug('Client user id is %s', request.auth.user.user_id) try: source_id, checksum = identifier.split('/', 1) except ValueError as e: ...
[ "def", "inner", "(", "identifier", ":", "str", ",", "owner_id", ":", "Optional", "[", "str", "]", ")", "->", "bool", ":", "logger", ".", "debug", "(", "'Authorize for %s owned by %s'", ",", "identifier", ",", "owner_id", ")", "logger", ".", "debug", "(", ...
Check whether the session is authorized for a specific resource.
[ "Check", "whether", "the", "session", "is", "authorized", "for", "a", "specific", "resource", "." ]
[ "\"\"\"Check whether the session is authorized for a specific resource.\"\"\"" ]
[ { "param": "identifier", "type": "str" }, { "param": "owner_id", "type": "Optional[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "identifier", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "owner_id", "type": "Optional[str]", "docstring": null, ...
d850a48868059577ef48f516a0a88dffa8f864d3
arXiv/arxiv-fulltext
fulltext/routes.py
[ "MIT" ]
Python
resource_id
str
def resource_id(id_type: str, identifier: str, *args: Any, **kw: Any) -> str: """Get the resource ID for an endpoint.""" if id_type == SupportedBuckets.SUBMISSION: return identifier.split('/', 1)[0] return identifier
Get the resource ID for an endpoint.
Get the resource ID for an endpoint.
[ "Get", "the", "resource", "ID", "for", "an", "endpoint", "." ]
def resource_id(id_type: str, identifier: str, *args: Any, **kw: Any) -> str: if id_type == SupportedBuckets.SUBMISSION: return identifier.split('/', 1)[0] return identifier
[ "def", "resource_id", "(", "id_type", ":", "str", ",", "identifier", ":", "str", ",", "*", "args", ":", "Any", ",", "**", "kw", ":", "Any", ")", "->", "str", ":", "if", "id_type", "==", "SupportedBuckets", ".", "SUBMISSION", ":", "return", "identifier"...
Get the resource ID for an endpoint.
[ "Get", "the", "resource", "ID", "for", "an", "endpoint", "." ]
[ "\"\"\"Get the resource ID for an endpoint.\"\"\"" ]
[ { "param": "id_type", "type": "str" }, { "param": "identifier", "type": "str" }, { "param": "args", "type": "Any" }, { "param": "kw", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "id_type", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "identifier", "type": "str", "docstring": null, "docstring...
d850a48868059577ef48f516a0a88dffa8f864d3
arXiv/arxiv-fulltext
fulltext/routes.py
[ "MIT" ]
Python
best_match
str
def best_match(available: List[str], default: str) -> str: """Determine best content type given Accept header and available types.""" if 'Accept' not in request.headers: return default ctype: str = request.accept_mimetypes.best_match(available) return ctype
Determine best content type given Accept header and available types.
Determine best content type given Accept header and available types.
[ "Determine", "best", "content", "type", "given", "Accept", "header", "and", "available", "types", "." ]
def best_match(available: List[str], default: str) -> str: if 'Accept' not in request.headers: return default ctype: str = request.accept_mimetypes.best_match(available) return ctype
[ "def", "best_match", "(", "available", ":", "List", "[", "str", "]", ",", "default", ":", "str", ")", "->", "str", ":", "if", "'Accept'", "not", "in", "request", ".", "headers", ":", "return", "default", "ctype", ":", "str", "=", "request", ".", "acc...
Determine best content type given Accept header and available types.
[ "Determine", "best", "content", "type", "given", "Accept", "header", "and", "available", "types", "." ]
[ "\"\"\"Determine best content type given Accept header and available types.\"\"\"" ]
[ { "param": "available", "type": "List[str]" }, { "param": "default", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "available", "type": "List[str]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "default", "type": "str", "docstring": null, "docs...
d850a48868059577ef48f516a0a88dffa8f864d3
arXiv/arxiv-fulltext
fulltext/routes.py
[ "MIT" ]
Python
ok
Response
def ok() -> Response: """Provide current integration status information for health checks.""" data, code, headers = controllers.service_status() response: Response = make_response(jsonify(data), code, headers) return response
Provide current integration status information for health checks.
Provide current integration status information for health checks.
[ "Provide", "current", "integration", "status", "information", "for", "health", "checks", "." ]
def ok() -> Response: data, code, headers = controllers.service_status() response: Response = make_response(jsonify(data), code, headers) return response
[ "def", "ok", "(", ")", "->", "Response", ":", "data", ",", "code", ",", "headers", "=", "controllers", ".", "service_status", "(", ")", "response", ":", "Response", "=", "make_response", "(", "jsonify", "(", "data", ")", ",", "code", ",", "headers", ")...
Provide current integration status information for health checks.
[ "Provide", "current", "integration", "status", "information", "for", "health", "checks", "." ]
[ "\"\"\"Provide current integration status information for health checks.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
d850a48868059577ef48f516a0a88dffa8f864d3
arXiv/arxiv-fulltext
fulltext/routes.py
[ "MIT" ]
Python
start_extraction
Response
def start_extraction(id_type: str, identifier: str) -> Response: """Handle requests for fulltext extraction.""" payload: Optional[dict] = request.get_json() force: bool = payload.get('force', False) if payload is not None else False token = request.environ['token'] # Authorization is required to wo...
Handle requests for fulltext extraction.
Handle requests for fulltext extraction.
[ "Handle", "requests", "for", "fulltext", "extraction", "." ]
def start_extraction(id_type: str, identifier: str) -> Response: payload: Optional[dict] = request.get_json() force: bool = payload.get('force', False) if payload is not None else False token = request.environ['token'] authorizer: Optional[Authorizer] = None if id_type == SupportedBuckets.SUBMISSION...
[ "def", "start_extraction", "(", "id_type", ":", "str", ",", "identifier", ":", "str", ")", "->", "Response", ":", "payload", ":", "Optional", "[", "dict", "]", "=", "request", ".", "get_json", "(", ")", "force", ":", "bool", "=", "payload", ".", "get",...
Handle requests for fulltext extraction.
[ "Handle", "requests", "for", "fulltext", "extraction", "." ]
[ "\"\"\"Handle requests for fulltext extraction.\"\"\"", "# Authorization is required to work with submissions." ]
[ { "param": "id_type", "type": "str" }, { "param": "identifier", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "id_type", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "identifier", "type": "str", "docstring": null, "docstring...
d850a48868059577ef48f516a0a88dffa8f864d3
arXiv/arxiv-fulltext
fulltext/routes.py
[ "MIT" ]
Python
retrieve
Response
def retrieve(id_type: str, identifier: str, version: Optional[str] = None, content_fmt: str = SupportedFormats.PLAIN) -> Response: """Retrieve full-text content for an arXiv paper.""" if identifier is None: raise BadRequest('identifier missing in request') available = ['application/json...
Retrieve full-text content for an arXiv paper.
Retrieve full-text content for an arXiv paper.
[ "Retrieve", "full", "-", "text", "content", "for", "an", "arXiv", "paper", "." ]
def retrieve(id_type: str, identifier: str, version: Optional[str] = None, content_fmt: str = SupportedFormats.PLAIN) -> Response: if identifier is None: raise BadRequest('identifier missing in request') available = ['application/json', 'text/plain'] content_type = best_match(available,...
[ "def", "retrieve", "(", "id_type", ":", "str", ",", "identifier", ":", "str", ",", "version", ":", "Optional", "[", "str", "]", "=", "None", ",", "content_fmt", ":", "str", "=", "SupportedFormats", ".", "PLAIN", ")", "->", "Response", ":", "if", "ident...
Retrieve full-text content for an arXiv paper.
[ "Retrieve", "full", "-", "text", "content", "for", "an", "arXiv", "paper", "." ]
[ "\"\"\"Retrieve full-text content for an arXiv paper.\"\"\"", "# Authorization is required to work with submissions." ]
[ { "param": "id_type", "type": "str" }, { "param": "identifier", "type": "str" }, { "param": "version", "type": "Optional[str]" }, { "param": "content_fmt", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "id_type", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "identifier", "type": "str", "docstring": null, "docstring...
d850a48868059577ef48f516a0a88dffa8f864d3
arXiv/arxiv-fulltext
fulltext/routes.py
[ "MIT" ]
Python
task_status
Response
def task_status(id_type: str, identifier: str, version: Optional[str] = None) -> Response: """Get the status of a text extraction task.""" # Authorization is required to work with submissions. authorizer: Optional[Authorizer] = None if id_type == SupportedBuckets.SUBMISSION: auth...
Get the status of a text extraction task.
Get the status of a text extraction task.
[ "Get", "the", "status", "of", "a", "text", "extraction", "task", "." ]
def task_status(id_type: str, identifier: str, version: Optional[str] = None) -> Response: authorizer: Optional[Authorizer] = None if id_type == SupportedBuckets.SUBMISSION: authorizer = make_authorizer(scopes.READ_COMPILE) data, code, headers = controllers.get_task_status(identifier...
[ "def", "task_status", "(", "id_type", ":", "str", ",", "identifier", ":", "str", ",", "version", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Response", ":", "authorizer", ":", "Optional", "[", "Authorizer", "]", "=", "None", "if", "id_ty...
Get the status of a text extraction task.
[ "Get", "the", "status", "of", "a", "text", "extraction", "task", "." ]
[ "\"\"\"Get the status of a text extraction task.\"\"\"", "# Authorization is required to work with submissions." ]
[ { "param": "id_type", "type": "str" }, { "param": "identifier", "type": "str" }, { "param": "version", "type": "Optional[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "id_type", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "identifier", "type": "str", "docstring": null, "docstring...
b66fc98e9f76021eecce9ba2d1128c75775ec942
arXiv/arxiv-fulltext
fulltext/agent/consumer.py
[ "MIT" ]
Python
update_secrets
bool
def update_secrets(self) -> bool: """Update any secrets that are out of date.""" got_new_secrets = False for key, value in self._secrets.yield_secrets(): if self._config.get(key) != value: got_new_secrets = True self._config[key] = value os.env...
Update any secrets that are out of date.
Update any secrets that are out of date.
[ "Update", "any", "secrets", "that", "are", "out", "of", "date", "." ]
def update_secrets(self) -> bool: got_new_secrets = False for key, value in self._secrets.yield_secrets(): if self._config.get(key) != value: got_new_secrets = True self._config[key] = value os.environ[key] = str(value) self._access_key = self....
[ "def", "update_secrets", "(", "self", ")", "->", "bool", ":", "got_new_secrets", "=", "False", "for", "key", ",", "value", "in", "self", ".", "_secrets", ".", "yield_secrets", "(", ")", ":", "if", "self", ".", "_config", ".", "get", "(", "key", ")", ...
Update any secrets that are out of date.
[ "Update", "any", "secrets", "that", "are", "out", "of", "date", "." ]
[ "\"\"\"Update any secrets that are out of date.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
b66fc98e9f76021eecce9ba2d1128c75775ec942
arXiv/arxiv-fulltext
fulltext/agent/consumer.py
[ "MIT" ]
Python
process_records
Tuple[str, int]
def process_records(self, start: str) -> Tuple[str, int]: """Update secrets before getting a new batch of records.""" if self._config.get('VAULT_ENABLED') and self.update_secrets(): # From the docs: # # > Unfortunately, IAM credentials are eventually consistent with ...
Update secrets before getting a new batch of records.
Update secrets before getting a new batch of records.
[ "Update", "secrets", "before", "getting", "a", "new", "batch", "of", "records", "." ]
def process_records(self, start: str) -> Tuple[str, int]: if self._config.get('VAULT_ENABLED') and self.update_secrets(): > Unfortunately, IAM credentials are eventually consistent with > respect to other Amazon services. If you are planning on using > these credential in ...
[ "def", "process_records", "(", "self", ",", "start", ":", "str", ")", "->", "Tuple", "[", "str", ",", "int", "]", ":", "if", "self", ".", "_config", ".", "get", "(", "'VAULT_ENABLED'", ")", "and", "self", ".", "update_secrets", "(", ")", ":", "time",...
Update secrets before getting a new batch of records.
[ "Update", "secrets", "before", "getting", "a", "new", "batch", "of", "records", "." ]
[ "\"\"\"Update secrets before getting a new batch of records.\"\"\"", "# From the docs:", "#", "# > Unfortunately, IAM credentials are eventually consistent with", "# > respect to other Amazon services. If you are planning on using", "# > these credential in a pipeline, you may need to add a delay of", "...
[ { "param": "self", "type": null }, { "param": "start", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "start", "type": "str", "docstring": null, "docstring_tokens":...
b66fc98e9f76021eecce9ba2d1128c75775ec942
arXiv/arxiv-fulltext
fulltext/agent/consumer.py
[ "MIT" ]
Python
process_record
None
def process_record(self, record: dict) -> None: """ Call for each record that is passed to process_records. Parameters ---------- data : bytes partition_key : bytes sequence_number : int sub_sequence_number : int Raises ------ Ind...
Call for each record that is passed to process_records. Parameters ---------- data : bytes partition_key : bytes sequence_number : int sub_sequence_number : int Raises ------ IndexingFailed Indexing of the document failed in ...
Call for each record that is passed to process_records. Parameters data : bytes partition_key : bytes sequence_number : int sub_sequence_number : int Raises IndexingFailed Indexing of the document failed in a way that indicates recovery is unlikely for subsequent papers, or too many individual documents failed.
[ "Call", "for", "each", "record", "that", "is", "passed", "to", "process_records", ".", "Parameters", "data", ":", "bytes", "partition_key", ":", "bytes", "sequence_number", ":", "int", "sub_sequence_number", ":", "int", "Raises", "IndexingFailed", "Indexing", "of"...
def process_record(self, record: dict) -> None: time.sleep(self.sleep) logger.debug(f'Processing record %s', record["SequenceNumber"]) try: deserialized = json.loads(record['Data'].decode('utf-8')) except json.decoder.JSONDecodeError as e: logger.error("Error whil...
[ "def", "process_record", "(", "self", ",", "record", ":", "dict", ")", "->", "None", ":", "time", ".", "sleep", "(", "self", ".", "sleep", ")", "logger", ".", "debug", "(", "f'Processing record %s'", ",", "record", "[", "\"SequenceNumber\"", "]", ")", "t...
Call for each record that is passed to process_records.
[ "Call", "for", "each", "record", "that", "is", "passed", "to", "process_records", "." ]
[ "\"\"\"\n Call for each record that is passed to process_records.\n\n Parameters\n ----------\n data : bytes\n partition_key : bytes\n sequence_number : int\n sub_sequence_number : int\n\n Raises\n ------\n IndexingFailed\n Indexing of...
[ { "param": "self", "type": null }, { "param": "record", "type": "dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "record", "type": "dict", "docstring": null, "docstring_tokens...
febd8e9920196c6891843ef012ccec4c806b4836
arXiv/arxiv-fulltext
fulltext/extract.py
[ "MIT" ]
Python
extract
Dict[str, str]
def extract(identifier: str, id_type: str, version: str, owner: Optional[str] = None, token: Optional[str] = None) -> Dict[str, str]: """Perform text extraction for a single arXiv document.""" logger.debug('Perform extraction for %s in bucket %s with version %s', identif...
Perform text extraction for a single arXiv document.
Perform text extraction for a single arXiv document.
[ "Perform", "text", "extraction", "for", "a", "single", "arXiv", "document", "." ]
def extract(identifier: str, id_type: str, version: str, owner: Optional[str] = None, token: Optional[str] = None) -> Dict[str, str]: logger.debug('Perform extraction for %s in bucket %s with version %s', identifier, id_type, version) storage = store.Storage.current_sess...
[ "def", "extract", "(", "identifier", ":", "str", ",", "id_type", ":", "str", ",", "version", ":", "str", ",", "owner", ":", "Optional", "[", "str", "]", "=", "None", ",", "token", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Dict", ...
Perform text extraction for a single arXiv document.
[ "Perform", "text", "extraction", "for", "a", "single", "arXiv", "document", "." ]
[ "\"\"\"Perform text extraction for a single arXiv document.\"\"\"", "# This assumes we have a metadata record on disk already.", "# Cleanup." ]
[ { "param": "identifier", "type": "str" }, { "param": "id_type", "type": "str" }, { "param": "version", "type": "str" }, { "param": "owner", "type": "Optional[str]" }, { "param": "token", "type": "Optional[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "identifier", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "id_type", "type": "str", "docstring": null, "docstring...
febd8e9920196c6891843ef012ccec4c806b4836
arXiv/arxiv-fulltext
fulltext/extract.py
[ "MIT" ]
Python
update_sent_state
None
def update_sent_state(sender: Optional[str] = None, headers: Optional[Dict[str, str]] = None, body: Any = None, **kwargs: Any) -> None: """Set state to SENT, so that we can tell whether a task exists.""" celery_app = get_or_create_worker_app(current_app) task = ce...
Set state to SENT, so that we can tell whether a task exists.
Set state to SENT, so that we can tell whether a task exists.
[ "Set", "state", "to", "SENT", "so", "that", "we", "can", "tell", "whether", "a", "task", "exists", "." ]
def update_sent_state(sender: Optional[str] = None, headers: Optional[Dict[str, str]] = None, body: Any = None, **kwargs: Any) -> None: celery_app = get_or_create_worker_app(current_app) task = celery_app.tasks.get(sender) backend = task.backend if task else celer...
[ "def", "update_sent_state", "(", "sender", ":", "Optional", "[", "str", "]", "=", "None", ",", "headers", ":", "Optional", "[", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ",", "body", ":", "Any", "=", "None", ",", "**", "kwargs", ":", ...
Set state to SENT, so that we can tell whether a task exists.
[ "Set", "state", "to", "SENT", "so", "that", "we", "can", "tell", "whether", "a", "task", "exists", "." ]
[ "\"\"\"Set state to SENT, so that we can tell whether a task exists.\"\"\"" ]
[ { "param": "sender", "type": "Optional[str]" }, { "param": "headers", "type": "Optional[Dict[str, str]]" }, { "param": "body", "type": "Any" }, { "param": "kwargs", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sender", "type": "Optional[str]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "headers", "type": "Optional[Dict[str, str]]", "docstri...
febd8e9920196c6891843ef012ccec4c806b4836
arXiv/arxiv-fulltext
fulltext/extract.py
[ "MIT" ]
Python
create_worker_app
Celery
def create_worker_app(app: Flask) -> Celery: """ Initialize the worker application. Returns ------- :class:`celery.Celery` """ result_backend = app.config['CELERY_RESULT_BACKEND'] broker = app.config['CELERY_BROKER_URL'] celery_app = Celery('fulltext', resul...
Initialize the worker application. Returns ------- :class:`celery.Celery`
Initialize the worker application. Returns
[ "Initialize", "the", "worker", "application", ".", "Returns" ]
def create_worker_app(app: Flask) -> Celery: result_backend = app.config['CELERY_RESULT_BACKEND'] broker = app.config['CELERY_BROKER_URL'] celery_app = Celery('fulltext', results=result_backend, backend=result_backend, result_backend=re...
[ "def", "create_worker_app", "(", "app", ":", "Flask", ")", "->", "Celery", ":", "result_backend", "=", "app", ".", "config", "[", "'CELERY_RESULT_BACKEND'", "]", "broker", "=", "app", ".", "config", "[", "'CELERY_BROKER_URL'", "]", "celery_app", "=", "Celery",...
Initialize the worker application.
[ "Initialize", "the", "worker", "application", "." ]
[ "\"\"\"\n Initialize the worker application.\n\n Returns\n -------\n :class:`celery.Celery`\n\n \"\"\"" ]
[ { "param": "app", "type": "Flask" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "app", "type": "Flask", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "class", "docstring": null, ...
518d629f61672afadd6716ea6912f666401fd245
arXiv/arxiv-fulltext
fulltext/services/preview/preview.py
[ "MIT" ]
Python
is_available
bool
def is_available(self, **kwargs: Any) -> bool: """Check our connection to the filesystem service.""" timeout: float = kwargs.get('timeout', 0.2) try: response = self.request('head', '/status', timeout=timeout) except Exception as e: logger.error('Encountered error...
Check our connection to the filesystem service.
Check our connection to the filesystem service.
[ "Check", "our", "connection", "to", "the", "filesystem", "service", "." ]
def is_available(self, **kwargs: Any) -> bool: timeout: float = kwargs.get('timeout', 0.2) try: response = self.request('head', '/status', timeout=timeout) except Exception as e: logger.error('Encountered error calling filesystem: %s', e) return False ...
[ "def", "is_available", "(", "self", ",", "**", "kwargs", ":", "Any", ")", "->", "bool", ":", "timeout", ":", "float", "=", "kwargs", ".", "get", "(", "'timeout'", ",", "0.2", ")", "try", ":", "response", "=", "self", ".", "request", "(", "'head'", ...
Check our connection to the filesystem service.
[ "Check", "our", "connection", "to", "the", "filesystem", "service", "." ]
[ "\"\"\"Check our connection to the filesystem service.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "kwargs", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "kwargs", "type": "Any", "docstring": null, "docstring_tokens"...
518d629f61672afadd6716ea6912f666401fd245
arXiv/arxiv-fulltext
fulltext/services/preview/preview.py
[ "MIT" ]
Python
does_exist
Tuple[bool, Optional[str]]
def does_exist(self, identifier: str, token: str) \ -> Tuple[bool, Optional[str]]: """ Determine whether or not a preview exists for an identifier. Parameters ---------- identifier : str Combination of the source ID and checksum: ``{source_id}...
Determine whether or not a preview exists for an identifier. Parameters ---------- identifier : str Combination of the source ID and checksum: ``{source_id}/{checksum}``, where ``source_id`` is the unique identifier of the source package from which t...
Determine whether or not a preview exists for an identifier. Parameters Returns bool str URL-safe base64-encoded MD5 hash of the preview content.
[ "Determine", "whether", "or", "not", "a", "preview", "exists", "for", "an", "identifier", ".", "Parameters", "Returns", "bool", "str", "URL", "-", "safe", "base64", "-", "encoded", "MD5", "hash", "of", "the", "preview", "content", "." ]
def does_exist(self, identifier: str, token: str) \ -> Tuple[bool, Optional[str]]: response = self.request('head', f'/{identifier}/content', token) if response.status_code == status.OK: return True, str(response.headers['ETag']) return False, None
[ "def", "does_exist", "(", "self", ",", "identifier", ":", "str", ",", "token", ":", "str", ")", "->", "Tuple", "[", "bool", ",", "Optional", "[", "str", "]", "]", ":", "response", "=", "self", ".", "request", "(", "'head'", ",", "f'/{identifier}/conten...
Determine whether or not a preview exists for an identifier.
[ "Determine", "whether", "or", "not", "a", "preview", "exists", "for", "an", "identifier", "." ]
[ "\"\"\"\n Determine whether or not a preview exists for an identifier.\n\n Parameters\n ----------\n identifier : str\n Combination of the source ID and checksum:\n ``{source_id}/{checksum}``, where ``source_id`` is the unique\n identifier of the source p...
[ { "param": "self", "type": null }, { "param": "identifier", "type": "str" }, { "param": "token", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "identifier", "type": "str", "docstring": null, "docstring_tok...
bcea6fbc291d07cbf8111bdbd6b4c2cfe47e85bc
arXiv/arxiv-fulltext
extractor/fulltext/fulltext.py
[ "MIT" ]
Python
average_word_length
<not_specific>
def average_word_length(txt): """ Gather statistics about the text, primarily the average word length Parameters ---------- txt : str Returns ------- word_length : float Average word length in the text """ txt = re.subn(RE_REPEATS, '', txt)[0] nw = len(txt.split()) ...
Gather statistics about the text, primarily the average word length Parameters ---------- txt : str Returns ------- word_length : float Average word length in the text
Gather statistics about the text, primarily the average word length Parameters txt : str Returns word_length : float Average word length in the text
[ "Gather", "statistics", "about", "the", "text", "primarily", "the", "average", "word", "length", "Parameters", "txt", ":", "str", "Returns", "word_length", ":", "float", "Average", "word", "length", "in", "the", "text" ]
def average_word_length(txt): txt = re.subn(RE_REPEATS, '', txt)[0] nw = len(txt.split()) nc = len(txt) avgw = nc / (nw + 1) return avgw
[ "def", "average_word_length", "(", "txt", ")", ":", "txt", "=", "re", ".", "subn", "(", "RE_REPEATS", ",", "''", ",", "txt", ")", "[", "0", "]", "nw", "=", "len", "(", "txt", ".", "split", "(", ")", ")", "nc", "=", "len", "(", "txt", ")", "av...
Gather statistics about the text, primarily the average word length Parameters
[ "Gather", "statistics", "about", "the", "text", "primarily", "the", "average", "word", "length", "Parameters" ]
[ "\"\"\"\n Gather statistics about the text, primarily the average word length\n\n Parameters\n ----------\n txt : str\n\n Returns\n -------\n word_length : float\n Average word length in the text\n \"\"\"" ]
[ { "param": "txt", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "txt", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
bcea6fbc291d07cbf8111bdbd6b4c2cfe47e85bc
arXiv/arxiv-fulltext
extractor/fulltext/fulltext.py
[ "MIT" ]
Python
run_pdf2txt
<not_specific>
def run_pdf2txt(pdffile: str, timelimit: int=TIMELIMIT, options: str=''): """ Run pdf2txt to extract full text Parameters ---------- pdffile : str Path to PDF file timelimit : int Amount of time to wait for the process to complete Returns ------- output : str ...
Run pdf2txt to extract full text Parameters ---------- pdffile : str Path to PDF file timelimit : int Amount of time to wait for the process to complete Returns ------- output : str Full plain text output
Run pdf2txt to extract full text Parameters pdffile : str Path to PDF file timelimit : int Amount of time to wait for the process to complete Returns output : str Full plain text output
[ "Run", "pdf2txt", "to", "extract", "full", "text", "Parameters", "pdffile", ":", "str", "Path", "to", "PDF", "file", "timelimit", ":", "int", "Amount", "of", "time", "to", "wait", "for", "the", "process", "to", "complete", "Returns", "output", ":", "str", ...
def run_pdf2txt(pdffile: str, timelimit: int=TIMELIMIT, options: str=''): log.debug('Running {} on {}'.format(PDF2TXT, pdffile)) tmpfile = reextension(pdffile, 'pdf2txt') cmd = '{cmd} {options} -o {output} {pdf}'.format( cmd=PDF2TXT, options=options, output=tmpfile, pdf=pdffile ) cmd = shlex...
[ "def", "run_pdf2txt", "(", "pdffile", ":", "str", ",", "timelimit", ":", "int", "=", "TIMELIMIT", ",", "options", ":", "str", "=", "''", ")", ":", "log", ".", "debug", "(", "'Running {} on {}'", ".", "format", "(", "PDF2TXT", ",", "pdffile", ")", ")", ...
Run pdf2txt to extract full text Parameters
[ "Run", "pdf2txt", "to", "extract", "full", "text", "Parameters" ]
[ "\"\"\"\n Run pdf2txt to extract full text\n\n Parameters\n ----------\n pdffile : str\n Path to PDF file\n\n timelimit : int\n Amount of time to wait for the process to complete\n\n Returns\n -------\n output : str\n Full plain text output\n \"\"\"" ]
[ { "param": "pdffile", "type": "str" }, { "param": "timelimit", "type": "int" }, { "param": "options", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pdffile", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "timelimit", "type": "int", "docstring": null, "docstring_...
bcea6fbc291d07cbf8111bdbd6b4c2cfe47e85bc
arXiv/arxiv-fulltext
extractor/fulltext/fulltext.py
[ "MIT" ]
Python
run_pdftotext
str
def run_pdftotext(pdffile: str, timelimit: int=TIMELIMIT) -> str: """ Run pdftotext on PDF file for extracted plain text Parameters ---------- pdffile : str Path to PDF file timelimit : int Amount of time to wait for the process to complete Returns ------- output :...
Run pdftotext on PDF file for extracted plain text Parameters ---------- pdffile : str Path to PDF file timelimit : int Amount of time to wait for the process to complete Returns ------- output : str Full plain text output
Run pdftotext on PDF file for extracted plain text Parameters pdffile : str Path to PDF file timelimit : int Amount of time to wait for the process to complete Returns output : str Full plain text output
[ "Run", "pdftotext", "on", "PDF", "file", "for", "extracted", "plain", "text", "Parameters", "pdffile", ":", "str", "Path", "to", "PDF", "file", "timelimit", ":", "int", "Amount", "of", "time", "to", "wait", "for", "the", "process", "to", "complete", "Retur...
def run_pdftotext(pdffile: str, timelimit: int=TIMELIMIT) -> str: log.debug('Running {} on {}'.format(PDFTOTEXT, pdffile)) tmpfile = reextension(pdffile, 'pdftotxt') cmd = '{cmd} {pdf} {output}'.format( cmd=PDFTOTEXT, pdf=pdffile, output=tmpfile ) cmd = shlex.split(cmd) output = check_ou...
[ "def", "run_pdftotext", "(", "pdffile", ":", "str", ",", "timelimit", ":", "int", "=", "TIMELIMIT", ")", "->", "str", ":", "log", ".", "debug", "(", "'Running {} on {}'", ".", "format", "(", "PDFTOTEXT", ",", "pdffile", ")", ")", "tmpfile", "=", "reexten...
Run pdftotext on PDF file for extracted plain text Parameters
[ "Run", "pdftotext", "on", "PDF", "file", "for", "extracted", "plain", "text", "Parameters" ]
[ "\"\"\"\n Run pdftotext on PDF file for extracted plain text\n\n Parameters\n ----------\n pdffile : str\n Path to PDF file\n\n timelimit : int\n Amount of time to wait for the process to complete\n\n Returns\n -------\n output : str\n Full plain text output\n \"\"\""...
[ { "param": "pdffile", "type": "str" }, { "param": "timelimit", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pdffile", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "timelimit", "type": "int", "docstring": null, "docstring_...
bcea6fbc291d07cbf8111bdbd6b4c2cfe47e85bc
arXiv/arxiv-fulltext
extractor/fulltext/fulltext.py
[ "MIT" ]
Python
fulltext
<not_specific>
def fulltext(pdffile: str, timelimit: int=TIMELIMIT): """ Given a pdf file, extract the unicode text and run through very basic unicode normalization routines. Determine the best extracted text and return as a string. Parameters ---------- pdffile : str Path to PDF file from which t...
Given a pdf file, extract the unicode text and run through very basic unicode normalization routines. Determine the best extracted text and return as a string. Parameters ---------- pdffile : str Path to PDF file from which to extract text timelimit : int Time in seconds t...
Given a pdf file, extract the unicode text and run through very basic unicode normalization routines. Determine the best extracted text and return as a string. Parameters pdffile : str Path to PDF file from which to extract text timelimit : int Time in seconds to allow the extraction routines to run Returns fullte...
[ "Given", "a", "pdf", "file", "extract", "the", "unicode", "text", "and", "run", "through", "very", "basic", "unicode", "normalization", "routines", ".", "Determine", "the", "best", "extracted", "text", "and", "return", "as", "a", "string", ".", "Parameters", ...
def fulltext(pdffile: str, timelimit: int=TIMELIMIT): if not os.path.isfile(pdffile): raise FileNotFoundError(pdffile) try: output = run_pdf2txt(pdffile, timelimit=timelimit) except (TimeoutExpired, CalledProcessError) as e: output = run_pdftotext(pdffile, timelimit=None) output ...
[ "def", "fulltext", "(", "pdffile", ":", "str", ",", "timelimit", ":", "int", "=", "TIMELIMIT", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "pdffile", ")", ":", "raise", "FileNotFoundError", "(", "pdffile", ")", "try", ":", "output", ...
Given a pdf file, extract the unicode text and run through very basic unicode normalization routines.
[ "Given", "a", "pdf", "file", "extract", "the", "unicode", "text", "and", "run", "through", "very", "basic", "unicode", "normalization", "routines", "." ]
[ "\"\"\"\n Given a pdf file, extract the unicode text and run through very basic\n unicode normalization routines. Determine the best extracted text and\n return as a string.\n\n Parameters\n ----------\n pdffile : str\n Path to PDF file from which to extract text\n\n timelimit : int\n ...
[ { "param": "pdffile", "type": "str" }, { "param": "timelimit", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pdffile", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "timelimit", "type": "int", "docstring": null, "docstring_...
bcea6fbc291d07cbf8111bdbd6b4c2cfe47e85bc
arXiv/arxiv-fulltext
extractor/fulltext/fulltext.py
[ "MIT" ]
Python
sorted_files
<not_specific>
def sorted_files(globber: str): """ Give a globbing expression of files to find. They will be sorted upon return. This function is most useful when sorting does not provide numerical order, e.g.: 9 -> 12 returned as 10 11 12 9 by string sort In this case use num_sort=True, and it will...
Give a globbing expression of files to find. They will be sorted upon return. This function is most useful when sorting does not provide numerical order, e.g.: 9 -> 12 returned as 10 11 12 9 by string sort In this case use num_sort=True, and it will be sorted by numbers in the string...
Give a globbing expression of files to find. They will be sorted upon return. This function is most useful when sorting does not provide numerical order. In this case use num_sort=True, and it will be sorted by numbers in the string, then by the string itself. Parameters globber : str Expression on which to searc...
[ "Give", "a", "globbing", "expression", "of", "files", "to", "find", ".", "They", "will", "be", "sorted", "upon", "return", ".", "This", "function", "is", "most", "useful", "when", "sorting", "does", "not", "provide", "numerical", "order", ".", "In", "this"...
def sorted_files(globber: str): files = glob.glob(globber) files.sort() allfiles = [] for fn in files: nums = re.findall(r'\d+', fn) data = [int(n) for n in nums] + [fn] allfiles.append(data) allfiles = sorted(allfiles) return [f[-1] for f in allfiles]
[ "def", "sorted_files", "(", "globber", ":", "str", ")", ":", "files", "=", "glob", ".", "glob", "(", "globber", ")", "files", ".", "sort", "(", ")", "allfiles", "=", "[", "]", "for", "fn", "in", "files", ":", "nums", "=", "re", ".", "findall", "(...
Give a globbing expression of files to find.
[ "Give", "a", "globbing", "expression", "of", "files", "to", "find", "." ]
[ "\"\"\"\n Give a globbing expression of files to find. They will be sorted upon\n return. This function is most useful when sorting does not provide\n numerical order,\n\n e.g.:\n 9 -> 12 returned as 10 11 12 9 by string sort\n\n In this case use num_sort=True, and it will be sorted by number...
[ { "param": "globber", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "globber", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
bcea6fbc291d07cbf8111bdbd6b4c2cfe47e85bc
arXiv/arxiv-fulltext
extractor/fulltext/fulltext.py
[ "MIT" ]
Python
convert_directory
<not_specific>
def convert_directory(path): """ Convert all pdfs in a given `path` to full plain text. For each pdf, a file of the same name but extension .txt will be created. If that file exists, it will be skipped. Parameters ---------- path : str Directory in which to search for pdfs and conve...
Convert all pdfs in a given `path` to full plain text. For each pdf, a file of the same name but extension .txt will be created. If that file exists, it will be skipped. Parameters ---------- path : str Directory in which to search for pdfs and convert to text Returns ------- ...
Convert all pdfs in a given `path` to full plain text. For each pdf, a file of the same name but extension .txt will be created. If that file exists, it will be skipped. Parameters path : str Directory in which to search for pdfs and convert to text Returns output : list of str List of converted files
[ "Convert", "all", "pdfs", "in", "a", "given", "`", "path", "`", "to", "full", "plain", "text", ".", "For", "each", "pdf", "a", "file", "of", "the", "same", "name", "but", "extension", ".", "txt", "will", "be", "created", ".", "If", "that", "file", ...
def convert_directory(path): outlist = [] globber = os.path.join(path, '*.pdf') pdffiles = sorted_files(globber) log.info('Searching "{}"...'.format(globber)) log.info('Found: {}'.format(pdffiles)) for pdffile in pdffiles: txtfile = reextension(pdffile, 'txt') if os.path.exists(t...
[ "def", "convert_directory", "(", "path", ")", ":", "outlist", "=", "[", "]", "globber", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'*.pdf'", ")", "pdffiles", "=", "sorted_files", "(", "globber", ")", "log", ".", "info", "(", "'Searching \"...
Convert all pdfs in a given `path` to full plain text.
[ "Convert", "all", "pdfs", "in", "a", "given", "`", "path", "`", "to", "full", "plain", "text", "." ]
[ "\"\"\"\n Convert all pdfs in a given `path` to full plain text. For each pdf, a file\n of the same name but extension .txt will be created. If that file exists,\n it will be skipped.\n\n Parameters\n ----------\n path : str\n Directory in which to search for pdfs and convert to text\n\n ...
[ { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
b019ca372aa5e7a67f7b97af89cdf5e2664defc5
arXiv/arxiv-fulltext
fulltext/services/extractor/extractor.py
[ "MIT" ]
Python
is_available
bool
def is_available(self, **kwargs: Any) -> bool: """Make sure that we can connect to the Docker API.""" try: self._new_client().info() except (APIError, ConnectionError) as e: logger.error('Error when connecting to Docker API: %s', e) return False return...
Make sure that we can connect to the Docker API.
Make sure that we can connect to the Docker API.
[ "Make", "sure", "that", "we", "can", "connect", "to", "the", "Docker", "API", "." ]
def is_available(self, **kwargs: Any) -> bool: try: self._new_client().info() except (APIError, ConnectionError) as e: logger.error('Error when connecting to Docker API: %s', e) return False return True
[ "def", "is_available", "(", "self", ",", "**", "kwargs", ":", "Any", ")", "->", "bool", ":", "try", ":", "self", ".", "_new_client", "(", ")", ".", "info", "(", ")", "except", "(", "APIError", ",", "ConnectionError", ")", "as", "e", ":", "logger", ...
Make sure that we can connect to the Docker API.
[ "Make", "sure", "that", "we", "can", "connect", "to", "the", "Docker", "API", "." ]
[ "\"\"\"Make sure that we can connect to the Docker API.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "kwargs", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "kwargs", "type": "Any", "docstring": null, "docstring_tokens"...
b019ca372aa5e7a67f7b97af89cdf5e2664defc5
arXiv/arxiv-fulltext
fulltext/services/extractor/extractor.py
[ "MIT" ]
Python
image
Tuple[str, str, str]
def image(self) -> Tuple[str, str, str]: """Get the name of the image used for extraction.""" image_name = current_app.config['EXTRACTOR_IMAGE'] image_tag = current_app.config['EXTRACTOR_VERSION'] return f'{image_name}:{image_tag}', image_name, image_tag
Get the name of the image used for extraction.
Get the name of the image used for extraction.
[ "Get", "the", "name", "of", "the", "image", "used", "for", "extraction", "." ]
def image(self) -> Tuple[str, str, str]: image_name = current_app.config['EXTRACTOR_IMAGE'] image_tag = current_app.config['EXTRACTOR_VERSION'] return f'{image_name}:{image_tag}', image_name, image_tag
[ "def", "image", "(", "self", ")", "->", "Tuple", "[", "str", ",", "str", ",", "str", "]", ":", "image_name", "=", "current_app", ".", "config", "[", "'EXTRACTOR_IMAGE'", "]", "image_tag", "=", "current_app", ".", "config", "[", "'EXTRACTOR_VERSION'", "]", ...
Get the name of the image used for extraction.
[ "Get", "the", "name", "of", "the", "image", "used", "for", "extraction", "." ]
[ "\"\"\"Get the name of the image used for extraction.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
b019ca372aa5e7a67f7b97af89cdf5e2664defc5
arXiv/arxiv-fulltext
fulltext/services/extractor/extractor.py
[ "MIT" ]
Python
_pull_image
None
def _pull_image(self, client: Optional[DockerClient] = None) -> None: """Tell the Docker API to pull our extraction image.""" if client is None: client = self._new_client() _, name, tag = self.image client.images.pull(name, tag)
Tell the Docker API to pull our extraction image.
Tell the Docker API to pull our extraction image.
[ "Tell", "the", "Docker", "API", "to", "pull", "our", "extraction", "image", "." ]
def _pull_image(self, client: Optional[DockerClient] = None) -> None: if client is None: client = self._new_client() _, name, tag = self.image client.images.pull(name, tag)
[ "def", "_pull_image", "(", "self", ",", "client", ":", "Optional", "[", "DockerClient", "]", "=", "None", ")", "->", "None", ":", "if", "client", "is", "None", ":", "client", "=", "self", ".", "_new_client", "(", ")", "_", ",", "name", ",", "tag", ...
Tell the Docker API to pull our extraction image.
[ "Tell", "the", "Docker", "API", "to", "pull", "our", "extraction", "image", "." ]
[ "\"\"\"Tell the Docker API to pull our extraction image.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "client", "type": "Optional[DockerClient]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "client", "type": "Optional[DockerClient]", "docstring": null, ...
e71feb2cb3ced373c152be261c8c6232695bcb9a
arXiv/arxiv-fulltext
fulltext/services/store/store.py
[ "MIT" ]
Python
is_available
bool
def is_available(self, **kwargs: Any) -> bool: """Determine whether storage is available.""" test_name = f'test-{datetime.timestamp(datetime.now(UTC))}' test_paper_path = self._paper_path('test', test_name) test_path = os.path.join(test_paper_path, test_name) try: sel...
Determine whether storage is available.
Determine whether storage is available.
[ "Determine", "whether", "storage", "is", "available", "." ]
def is_available(self, **kwargs: Any) -> bool: test_name = f'test-{datetime.timestamp(datetime.now(UTC))}' test_paper_path = self._paper_path('test', test_name) test_path = os.path.join(test_paper_path, test_name) try: self._store(test_path, 'test_name') except Storag...
[ "def", "is_available", "(", "self", ",", "**", "kwargs", ":", "Any", ")", "->", "bool", ":", "test_name", "=", "f'test-{datetime.timestamp(datetime.now(UTC))}'", "test_paper_path", "=", "self", ".", "_paper_path", "(", "'test'", ",", "test_name", ")", "test_path",...
Determine whether storage is available.
[ "Determine", "whether", "storage", "is", "available", "." ]
[ "\"\"\"Determine whether storage is available.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "kwargs", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "kwargs", "type": "Any", "docstring": null, "docstring_tokens"...
e71feb2cb3ced373c152be261c8c6232695bcb9a
arXiv/arxiv-fulltext
fulltext/services/store/store.py
[ "MIT" ]
Python
_paper_path
str
def _paper_path(self, identifier: str, bucket: str) -> str: """ Generate a base path for extraction from a particular resource. This should generate paths like: - Old-style e-print: /{volume}/arxiv/alg-geom/9204/9204001v2 - New-style e-print: /{volume}/arxiv/1801/00123v1 ...
Generate a base path for extraction from a particular resource. This should generate paths like: - Old-style e-print: /{volume}/arxiv/alg-geom/9204/9204001v2 - New-style e-print: /{volume}/arxiv/1801/00123v1 - Anything else: /{volume}/{bucket}/{identifier}
Generate a base path for extraction from a particular resource. This should generate paths like.
[ "Generate", "a", "base", "path", "for", "extraction", "from", "a", "particular", "resource", ".", "This", "should", "generate", "paths", "like", "." ]
def _paper_path(self, identifier: str, bucket: str) -> str: if OLD_STYLE.match(identifier): pre, num = identifier.split('/', 1) return os.path.join(self._volume, bucket, pre, num[:4], num) elif STANDARD.match(identifier): prefix = identifier.split('.', 1)[0] ...
[ "def", "_paper_path", "(", "self", ",", "identifier", ":", "str", ",", "bucket", ":", "str", ")", "->", "str", ":", "if", "OLD_STYLE", ".", "match", "(", "identifier", ")", ":", "pre", ",", "num", "=", "identifier", ".", "split", "(", "'/'", ",", "...
Generate a base path for extraction from a particular resource.
[ "Generate", "a", "base", "path", "for", "extraction", "from", "a", "particular", "resource", "." ]
[ "\"\"\"\n Generate a base path for extraction from a particular resource.\n\n This should generate paths like:\n\n - Old-style e-print: /{volume}/arxiv/alg-geom/9204/9204001v2\n - New-style e-print: /{volume}/arxiv/1801/00123v1\n - Anything else: /{volume}/{bucket}/{identifier}\n\...
[ { "param": "self", "type": null }, { "param": "identifier", "type": "str" }, { "param": "bucket", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "identifier", "type": "str", "docstring": null, "docstring_tok...
e71feb2cb3ced373c152be261c8c6232695bcb9a
arXiv/arxiv-fulltext
fulltext/services/store/store.py
[ "MIT" ]
Python
make_paths
None
def make_paths(path: str) -> None: """Create any missing directories containing terminal ``path``.""" parent, _ = os.path.split(path) if not os.path.exists(parent): logger.debug('Make paths to %s', parent) os.makedirs(parent)
Create any missing directories containing terminal ``path``.
Create any missing directories containing terminal ``path``.
[ "Create", "any", "missing", "directories", "containing", "terminal", "`", "`", "path", "`", "`", "." ]
def make_paths(path: str) -> None: parent, _ = os.path.split(path) if not os.path.exists(parent): logger.debug('Make paths to %s', parent) os.makedirs(parent)
[ "def", "make_paths", "(", "path", ":", "str", ")", "->", "None", ":", "parent", ",", "_", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "parent", ")", ":", "logger", ".", "debug", "(...
Create any missing directories containing terminal ``path``.
[ "Create", "any", "missing", "directories", "containing", "terminal", "`", "`", "path", "`", "`", "." ]
[ "\"\"\"Create any missing directories containing terminal ``path``.\"\"\"" ]
[ { "param": "path", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "path", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2d14e1729e00e390b06eb7e1bc70f046814f3fb1
arXiv/arxiv-fulltext
fulltext/services/legacy/legacy.py
[ "MIT" ]
Python
is_available
bool
def is_available(self, **kwargs: Any) -> bool: """Determine whether canonical PDFs are available.""" timeout: float = kwargs.get('timeout', 2.0) response = self._session.head(self._path(f'/'), allow_redirects=True, timeout=timeout) return bool(respon...
Determine whether canonical PDFs are available.
Determine whether canonical PDFs are available.
[ "Determine", "whether", "canonical", "PDFs", "are", "available", "." ]
def is_available(self, **kwargs: Any) -> bool: timeout: float = kwargs.get('timeout', 2.0) response = self._session.head(self._path(f'/'), allow_redirects=True, timeout=timeout) return bool(response.status_code == status.OK)
[ "def", "is_available", "(", "self", ",", "**", "kwargs", ":", "Any", ")", "->", "bool", ":", "timeout", ":", "float", "=", "kwargs", ".", "get", "(", "'timeout'", ",", "2.0", ")", "response", "=", "self", ".", "_session", ".", "head", "(", "self", ...
Determine whether canonical PDFs are available.
[ "Determine", "whether", "canonical", "PDFs", "are", "available", "." ]
[ "\"\"\"Determine whether canonical PDFs are available.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "kwargs", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "kwargs", "type": "Any", "docstring": null, "docstring_tokens"...
2d14e1729e00e390b06eb7e1bc70f046814f3fb1
arXiv/arxiv-fulltext
fulltext/services/legacy/legacy.py
[ "MIT" ]
Python
exists
bool
def exists(self, identifier: str) -> bool: """ Determine whether or not a target URL is available (HEAD request). Parameters ---------- identifier : str arXiv identifier for which a PDF is required. Returns ------- bool """ r...
Determine whether or not a target URL is available (HEAD request). Parameters ---------- identifier : str arXiv identifier for which a PDF is required. Returns ------- bool
Determine whether or not a target URL is available (HEAD request). Parameters identifier : str arXiv identifier for which a PDF is required. Returns bool
[ "Determine", "whether", "or", "not", "a", "target", "URL", "is", "available", "(", "HEAD", "request", ")", ".", "Parameters", "identifier", ":", "str", "arXiv", "identifier", "for", "which", "a", "PDF", "is", "required", ".", "Returns", "bool" ]
def exists(self, identifier: str) -> bool: r = self._session.head(self._path(f'/pdf/{identifier}'), allow_redirects=True) if r.status_code == status.OK: return True if r.status_code == status.NOT_FOUND: return False raise IOError(f'U...
[ "def", "exists", "(", "self", ",", "identifier", ":", "str", ")", "->", "bool", ":", "r", "=", "self", ".", "_session", ".", "head", "(", "self", ".", "_path", "(", "f'/pdf/{identifier}'", ")", ",", "allow_redirects", "=", "True", ")", "if", "r", "."...
Determine whether or not a target URL is available (HEAD request).
[ "Determine", "whether", "or", "not", "a", "target", "URL", "is", "available", "(", "HEAD", "request", ")", "." ]
[ "\"\"\"\n Determine whether or not a target URL is available (HEAD request).\n\n Parameters\n ----------\n identifier : str\n arXiv identifier for which a PDF is required.\n\n Returns\n -------\n bool\n\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "identifier", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "identifier", "type": "str", "docstring": null, "docstring_tok...
2d14e1729e00e390b06eb7e1bc70f046814f3fb1
arXiv/arxiv-fulltext
fulltext/services/legacy/legacy.py
[ "MIT" ]
Python
retrieve
IO[bytes]
def retrieve(self, identifier: str, sleep: int = 5) -> IO[bytes]: """ Retrieve PDFs of published papers from the core arXiv document store. Parameters ---------- identifier : str arXiv identifier for which a PDF is required. Returns ------- s...
Retrieve PDFs of published papers from the core arXiv document store. Parameters ---------- identifier : str arXiv identifier for which a PDF is required. Returns ------- str Path to (temporary) PDF. Raises ------ ...
Retrieve PDFs of published papers from the core arXiv document store. Parameters identifier : str arXiv identifier for which a PDF is required. Returns str Path to (temporary) PDF. Raises ValueError If a disallowed or otherwise invalid URL is passed. IOError When there is a problem retrieving the resource at ``tar...
[ "Retrieve", "PDFs", "of", "published", "papers", "from", "the", "core", "arXiv", "document", "store", ".", "Parameters", "identifier", ":", "str", "arXiv", "identifier", "for", "which", "a", "PDF", "is", "required", ".", "Returns", "str", "Path", "to", "(", ...
def retrieve(self, identifier: str, sleep: int = 5) -> IO[bytes]: target = self._path(f'/pdf/{identifier}') pdf_response = self._session.get(target) if pdf_response.status_code == status.NOT_FOUND: logger.info('Could not retrieve PDF for %s', identifier) raise DoesNotExis...
[ "def", "retrieve", "(", "self", ",", "identifier", ":", "str", ",", "sleep", ":", "int", "=", "5", ")", "->", "IO", "[", "bytes", "]", ":", "target", "=", "self", ".", "_path", "(", "f'/pdf/{identifier}'", ")", "pdf_response", "=", "self", ".", "_ses...
Retrieve PDFs of published papers from the core arXiv document store.
[ "Retrieve", "PDFs", "of", "published", "papers", "from", "the", "core", "arXiv", "document", "store", "." ]
[ "\"\"\"\n Retrieve PDFs of published papers from the core arXiv document store.\n\n Parameters\n ----------\n identifier : str\n arXiv identifier for which a PDF is required.\n\n Returns\n -------\n str\n Path to (temporary) PDF.\n\n Rais...
[ { "param": "self", "type": null }, { "param": "identifier", "type": "str" }, { "param": "sleep", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "identifier", "type": "str", "docstring": null, "docstring_tok...
959ce42e6d7adf1e4abaa44de2d562e21aa6ac89
arXiv/arxiv-fulltext
fulltext/process/psv.py
[ "MIT" ]
Python
process_text
Tuple[str, str]
def process_text(txt: str) -> Tuple[str, str]: """ Convert a single string to a list of lines giving the PSV and references. Parameters ---------- txt : string The full text of an article, typically as extracted from PDF Returns ------- psv : string The extracted PSV as...
Convert a single string to a list of lines giving the PSV and references. Parameters ---------- txt : string The full text of an article, typically as extracted from PDF Returns ------- psv : string The extracted PSV as a single string object ref : string The ...
Convert a single string to a list of lines giving the PSV and references. Parameters txt : string The full text of an article, typically as extracted from PDF Returns psv : string The extracted PSV as a single string object ref : string The cleaned reference section with lines separated by newline
[ "Convert", "a", "single", "string", "to", "a", "list", "of", "lines", "giving", "the", "PSV", "and", "references", ".", "Parameters", "txt", ":", "string", "The", "full", "text", "of", "an", "article", "typically", "as", "extracted", "from", "PDF", "Return...
def process_text(txt: str) -> Tuple[str, str]: txt = _recover_accents(txt) lines = [l+'\n' for l in re.split(r'[\x0a-\x0d]+', txt)] psv, ref = split_on_references(lines) psv_composed = '\n'.join(tidy_txt_from_pdf(psv)) ref_composed = '\n'.join(tidy_txt_from_pdf(ref)) return psv_composed, ref_com...
[ "def", "process_text", "(", "txt", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "txt", "=", "_recover_accents", "(", "txt", ")", "lines", "=", "[", "l", "+", "'\\n'", "for", "l", "in", "re", ".", "split", "(", "r'[\\x0a-\\x0d]+...
Convert a single string to a list of lines giving the PSV and references.
[ "Convert", "a", "single", "string", "to", "a", "list", "of", "lines", "giving", "the", "PSV", "and", "references", "." ]
[ "\"\"\"\n Convert a single string to a list of lines giving the PSV and references.\n\n Parameters\n ----------\n txt : string\n The full text of an article, typically as extracted from PDF\n\n Returns\n -------\n psv : string\n The extracted PSV as a single string object\n\n r...
[ { "param": "txt", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "txt", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
959ce42e6d7adf1e4abaa44de2d562e21aa6ac89
arXiv/arxiv-fulltext
fulltext/process/psv.py
[ "MIT" ]
Python
_remove_WhiteSpace
List[str]
def _remove_WhiteSpace(lines: List[str]) -> List[str]: """Change white spaces, including eols, to spaces.""" out = [] for line in lines: out.append(re.subn(r'[\n\r\f\t]', ' ', line)[0]) return out
Change white spaces, including eols, to spaces.
Change white spaces, including eols, to spaces.
[ "Change", "white", "spaces", "including", "eols", "to", "spaces", "." ]
def _remove_WhiteSpace(lines: List[str]) -> List[str]: out = [] for line in lines: out.append(re.subn(r'[\n\r\f\t]', ' ', line)[0]) return out
[ "def", "_remove_WhiteSpace", "(", "lines", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "out", "=", "[", "]", "for", "line", "in", "lines", ":", "out", ".", "append", "(", "re", ".", "subn", "(", "r'[\\n\\r\\f\\t]'", ",", ...
Change white spaces, including eols, to spaces.
[ "Change", "white", "spaces", "including", "eols", "to", "spaces", "." ]
[ "\"\"\"Change white spaces, including eols, to spaces.\"\"\"" ]
[ { "param": "lines", "type": "List[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lines", "type": "List[str]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
959ce42e6d7adf1e4abaa44de2d562e21aa6ac89
arXiv/arxiv-fulltext
fulltext/process/psv.py
[ "MIT" ]
Python
_remove_BadEOL
List[str]
def _remove_BadEOL(lines: List[str]) -> List[str]: """Remove eols in the middle of sentence.""" out = [''] prevline = '' for line in lines: line = re.sub(r'- $', '', line) if re.match(r'^[a-z]', line) and not re.match(r'\. $', prevline): out.append(out.pop() + line) ...
Remove eols in the middle of sentence.
Remove eols in the middle of sentence.
[ "Remove", "eols", "in", "the", "middle", "of", "sentence", "." ]
def _remove_BadEOL(lines: List[str]) -> List[str]: out = [''] prevline = '' for line in lines: line = re.sub(r'- $', '', line) if re.match(r'^[a-z]', line) and not re.match(r'\. $', prevline): out.append(out.pop() + line) else: out.append(line) prevlin...
[ "def", "_remove_BadEOL", "(", "lines", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "out", "=", "[", "''", "]", "prevline", "=", "''", "for", "line", "in", "lines", ":", "line", "=", "re", ".", "sub", "(", "r'- $'", ",...
Remove eols in the middle of sentence.
[ "Remove", "eols", "in", "the", "middle", "of", "sentence", "." ]
[ "\"\"\"Remove eols in the middle of sentence.\"\"\"" ]
[ { "param": "lines", "type": "List[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lines", "type": "List[str]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
959ce42e6d7adf1e4abaa44de2d562e21aa6ac89
arXiv/arxiv-fulltext
fulltext/process/psv.py
[ "MIT" ]
Python
_remove_Keyword
List[str]
def _remove_Keyword(lines: List[str]) -> List[str]: """Remove sentences with the following keywords.""" out = [] prevline = '' saveline = '' for line in lines: prevline = saveline saveline = line if line.lower().startswith('arxiv'): continue if 'will be ...
Remove sentences with the following keywords.
Remove sentences with the following keywords.
[ "Remove", "sentences", "with", "the", "following", "keywords", "." ]
def _remove_Keyword(lines: List[str]) -> List[str]: out = [] prevline = '' saveline = '' for line in lines: prevline = saveline saveline = line if line.lower().startswith('arxiv'): continue if 'will be inserted by hand later' in line: continue ...
[ "def", "_remove_Keyword", "(", "lines", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "out", "=", "[", "]", "prevline", "=", "''", "saveline", "=", "''", "for", "line", "in", "lines", ":", "prevline", "=", "saveline", "save...
Remove sentences with the following keywords.
[ "Remove", "sentences", "with", "the", "following", "keywords", "." ]
[ "\"\"\"Remove sentences with the following keywords.\"\"\"" ]
[ { "param": "lines", "type": "List[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lines", "type": "List[str]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
959ce42e6d7adf1e4abaa44de2d562e21aa6ac89
arXiv/arxiv-fulltext
fulltext/process/psv.py
[ "MIT" ]
Python
_clean_sentence
List[str]
def _clean_sentence(lines: List[str]) -> List[str]: """Remove non-alphabet from the sentences. Convert to lower-case.""" out: List[str] = [] for line in lines: # continue if the line does not have any words if not re.match(r'\w', line): continue # replace all non-alphabe...
Remove non-alphabet from the sentences. Convert to lower-case.
Remove non-alphabet from the sentences. Convert to lower-case.
[ "Remove", "non", "-", "alphabet", "from", "the", "sentences", ".", "Convert", "to", "lower", "-", "case", "." ]
def _clean_sentence(lines: List[str]) -> List[str]: out: List[str] = [] for line in lines: if not re.match(r'\w', line): continue line = re.subn(r'\W', ' ', line)[0] line = _remove_ExtraSpaces(line) line = re.sub(r'^\s+', '', line) line = re.sub(r'\s+$', '', l...
[ "def", "_clean_sentence", "(", "lines", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "out", ":", "List", "[", "str", "]", "=", "[", "]", "for", "line", "in", "lines", ":", "if", "not", "re", ".", "match", "(", "r'\\w'"...
Remove non-alphabet from the sentences.
[ "Remove", "non", "-", "alphabet", "from", "the", "sentences", "." ]
[ "\"\"\"Remove non-alphabet from the sentences. Convert to lower-case.\"\"\"", "# continue if the line does not have any words", "# replace all non-alphabet to space", "# remove all space in the beginning and end of the sentence", "# Remove \"sentences\" that has less than or equal to 3 characters" ]
[ { "param": "lines", "type": "List[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lines", "type": "List[str]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
959ce42e6d7adf1e4abaa44de2d562e21aa6ac89
arXiv/arxiv-fulltext
fulltext/process/psv.py
[ "MIT" ]
Python
split_on_references
Tuple[List[str], List[str]]
def split_on_references(lines: List[str], max_refs_fraction: float = 0.5) \ -> Tuple[List[str], List[str]]: """ Mark the start of the references. Does this by looking for the last occurrence of the word "Reference" or "Bibliography". """ regex_refsection = re.compile( r'^[^a-zA-...
Mark the start of the references. Does this by looking for the last occurrence of the word "Reference" or "Bibliography".
Mark the start of the references. Does this by looking for the last occurrence of the word "Reference" or "Bibliography".
[ "Mark", "the", "start", "of", "the", "references", ".", "Does", "this", "by", "looking", "for", "the", "last", "occurrence", "of", "the", "word", "\"", "Reference", "\"", "or", "\"", "Bibliography", "\"", "." ]
def split_on_references(lines: List[str], max_refs_fraction: float = 0.5) \ -> Tuple[List[str], List[str]]: regex_refsection = re.compile( r'^[^a-zA-Z]*(Reference[s]?|Bibliography)[\W]*$', flags=re.IGNORECASE ) psv: List[str] = [] ref: List[str] = [] line_num = 0 last_refs = 0 ...
[ "def", "split_on_references", "(", "lines", ":", "List", "[", "str", "]", ",", "max_refs_fraction", ":", "float", "=", "0.5", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "List", "[", "str", "]", "]", ":", "regex_refsection", "=", "re", "."...
Mark the start of the references.
[ "Mark", "the", "start", "of", "the", "references", "." ]
[ "\"\"\"\n Mark the start of the references.\n\n Does this by looking for the last occurrence of the word \"Reference\" or\n \"Bibliography\".\n \"\"\"" ]
[ { "param": "lines", "type": "List[str]" }, { "param": "max_refs_fraction", "type": "float" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lines", "type": "List[str]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "max_refs_fraction", "type": "float", "docstring": null, ...
959ce42e6d7adf1e4abaa44de2d562e21aa6ac89
arXiv/arxiv-fulltext
fulltext/process/psv.py
[ "MIT" ]
Python
_recover_accents
str
def _recover_accents(txt: str) -> str: """ Try to recover plain text with garbled accents. Hack to try to recover plain text with accents removed from various outputs from xpdf pdf->txt which garble accented characters into multi-byte sequences often including linefeed characeters """ # uml...
Try to recover plain text with garbled accents. Hack to try to recover plain text with accents removed from various outputs from xpdf pdf->txt which garble accented characters into multi-byte sequences often including linefeed characeters
Try to recover plain text with garbled accents. Hack to try to recover plain text with accents removed from various outputs from xpdf pdf->txt which garble accented characters into multi-byte sequences often including linefeed characeters
[ "Try", "to", "recover", "plain", "text", "with", "garbled", "accents", ".", "Hack", "to", "try", "to", "recover", "plain", "text", "with", "accents", "removed", "from", "various", "outputs", "from", "xpdf", "pdf", "-", ">", "txt", "which", "garble", "accen...
def _recover_accents(txt: str) -> str: txt = re.subn(r'[\xa8|\xb4|\xb8|\xb0]\x0a?', '', txt)[0] txt = re.subn(r'[\x5e|\x60|\x7e]\x0a', '', txt)[0] txt = txt.replace('\xf8', 'o') txt = txt.replace('\xd8', 'O') txt = txt.replace('\xdf', 'ss') txt = txt.replace('\xe6', 'ae') txt = txt.replace('...
[ "def", "_recover_accents", "(", "txt", ":", "str", ")", "->", "str", ":", "txt", "=", "re", ".", "subn", "(", "r'[\\xa8|\\xb4|\\xb8|\\xb0]\\x0a?'", ",", "''", ",", "txt", ")", "[", "0", "]", "txt", "=", "re", ".", "subn", "(", "r'[\\x5e|\\x60|\\x7e]\\x0a...
Try to recover plain text with garbled accents.
[ "Try", "to", "recover", "plain", "text", "with", "garbled", "accents", "." ]
[ "\"\"\"\n Try to recover plain text with garbled accents.\n\n Hack to try to recover plain text with accents removed from various\n outputs from xpdf pdf->txt which garble accented characters into multi-byte\n sequences often including linefeed characeters\n \"\"\"", "# umlaut, acute, cedilla, Angs...
[ { "param": "txt", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "txt", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ad0145f92a04ec41b62530920fac43f00bca4c97
arXiv/arxiv-fulltext
fulltext/controllers.py
[ "MIT" ]
Python
service_status
Response
def service_status() -> Response: """Handle a request for the status of this service.""" # This is the critical upstream integration. stat = { 'storage': store.Storage.current_session().is_available(), 'extractor': extract.is_available(await_result=True) } if all(stat.values()): ...
Handle a request for the status of this service.
Handle a request for the status of this service.
[ "Handle", "a", "request", "for", "the", "status", "of", "this", "service", "." ]
def service_status() -> Response: stat = { 'storage': store.Storage.current_session().is_available(), 'extractor': extract.is_available(await_result=True) } if all(stat.values()): return stat, status.OK, {} raise InternalServerError(stat)
[ "def", "service_status", "(", ")", "->", "Response", ":", "stat", "=", "{", "'storage'", ":", "store", ".", "Storage", ".", "current_session", "(", ")", ".", "is_available", "(", ")", ",", "'extractor'", ":", "extract", ".", "is_available", "(", "await_res...
Handle a request for the status of this service.
[ "Handle", "a", "request", "for", "the", "status", "of", "this", "service", "." ]
[ "\"\"\"Handle a request for the status of this service.\"\"\"", "# This is the critical upstream integration.", "# type: ignore" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
ad0145f92a04ec41b62530920fac43f00bca4c97
arXiv/arxiv-fulltext
fulltext/controllers.py
[ "MIT" ]
Python
start_extraction
Response
def start_extraction(id_type: str, identifier: str, token: str, force: bool = False, authorizer: Optional[Authorizer] = None) -> Response: """Handle a request to force text extraction.""" if id_type not in SupportedBuckets: raise NotFound('Unsupported identifier...
Handle a request to force text extraction.
Handle a request to force text extraction.
[ "Handle", "a", "request", "to", "force", "text", "extraction", "." ]
def start_extraction(id_type: str, identifier: str, token: str, force: bool = False, authorizer: Optional[Authorizer] = None) -> Response: if id_type not in SupportedBuckets: raise NotFound('Unsupported identifier') canonical = legacy.CanonicalPDF.current_sessio...
[ "def", "start_extraction", "(", "id_type", ":", "str", ",", "identifier", ":", "str", ",", "token", ":", "str", ",", "force", ":", "bool", "=", "False", ",", "authorizer", ":", "Optional", "[", "Authorizer", "]", "=", "None", ")", "->", "Response", ":"...
Handle a request to force text extraction.
[ "Handle", "a", "request", "to", "force", "text", "extraction", "." ]
[ "\"\"\"Handle a request to force text extraction.\"\"\"", "# Before creating an extraction task, check that the intended document", "# even exists. This gives the client a clear failure now, rather than", "# waiting until the async task fails. At the same time, we'll also grab", "# the owner (if there is on...
[ { "param": "id_type", "type": "str" }, { "param": "identifier", "type": "str" }, { "param": "token", "type": "str" }, { "param": "force", "type": "bool" }, { "param": "authorizer", "type": "Optional[Authorizer]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "id_type", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "identifier", "type": "str", "docstring": null, "docstring...
55ab4d69e7c28c70a2884e87411e2192537742c7
arXiv/arxiv-fulltext
fulltext/worker.py
[ "MIT" ]
Python
pull_image
None
def pull_image(*args: Any, **kwargs: Any) -> None: """Make the dind host pull the fulltext extractor image.""" client = docker.DockerClient(app.config['DOCKER_HOST']) image_name = app.config['EXTRACTOR_IMAGE'] image_tag = app.config['EXTRACTOR_VERSION'] logger.info('Pulling %s', f'{image_name}:{imag...
Make the dind host pull the fulltext extractor image.
Make the dind host pull the fulltext extractor image.
[ "Make", "the", "dind", "host", "pull", "the", "fulltext", "extractor", "image", "." ]
def pull_image(*args: Any, **kwargs: Any) -> None: client = docker.DockerClient(app.config['DOCKER_HOST']) image_name = app.config['EXTRACTOR_IMAGE'] image_tag = app.config['EXTRACTOR_VERSION'] logger.info('Pulling %s', f'{image_name}:{image_tag}') for line in client.images.pull(f'{image_name}:{imag...
[ "def", "pull_image", "(", "*", "args", ":", "Any", ",", "**", "kwargs", ":", "Any", ")", "->", "None", ":", "client", "=", "docker", ".", "DockerClient", "(", "app", ".", "config", "[", "'DOCKER_HOST'", "]", ")", "image_name", "=", "app", ".", "confi...
Make the dind host pull the fulltext extractor image.
[ "Make", "the", "dind", "host", "pull", "the", "fulltext", "extractor", "image", "." ]
[ "\"\"\"Make the dind host pull the fulltext extractor image.\"\"\"" ]
[ { "param": "args", "type": "Any" }, { "param": "kwargs", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "args", "type": "Any", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "kwargs", "type": "Any", "docstring": null, "docstring_tokens...
55ab4d69e7c28c70a2884e87411e2192537742c7
arXiv/arxiv-fulltext
fulltext/worker.py
[ "MIT" ]
Python
verify_secrets_up_to_date
None
def verify_secrets_up_to_date(*args: Any, **kwargs: Any) -> None: """Verify that any required secrets from Vault are up to date.""" logger.debug('Veryifying that secrets are up to date') if not app.config['VAULT_ENABLED']: print('Vault not enabled; skipping') return for key, value in __...
Verify that any required secrets from Vault are up to date.
Verify that any required secrets from Vault are up to date.
[ "Verify", "that", "any", "required", "secrets", "from", "Vault", "are", "up", "to", "date", "." ]
def verify_secrets_up_to_date(*args: Any, **kwargs: Any) -> None: logger.debug('Veryifying that secrets are up to date') if not app.config['VAULT_ENABLED']: print('Vault not enabled; skipping') return for key, value in __secrets__.yield_secrets(): app.config[key] = value
[ "def", "verify_secrets_up_to_date", "(", "*", "args", ":", "Any", ",", "**", "kwargs", ":", "Any", ")", "->", "None", ":", "logger", ".", "debug", "(", "'Veryifying that secrets are up to date'", ")", "if", "not", "app", ".", "config", "[", "'VAULT_ENABLED'", ...
Verify that any required secrets from Vault are up to date.
[ "Verify", "that", "any", "required", "secrets", "from", "Vault", "are", "up", "to", "date", "." ]
[ "\"\"\"Verify that any required secrets from Vault are up to date.\"\"\"", "# type: ignore" ]
[ { "param": "args", "type": "Any" }, { "param": "kwargs", "type": "Any" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "args", "type": "Any", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "kwargs", "type": "Any", "docstring": null, "docstring_tokens...
073796e770e4aad6c6dec78adfd291a49c284243
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/malwaredomains.py
[ "MIT" ]
Python
connect_to_mongodb
<not_specific>
def connect_to_mongodb(): """ This function implements the connection to mongoDB @returns connection (MongoClient or None) a MongoClient object to handle the connection. None on failure """ # connect to database try: connection = MongoClient('XXX.XXX.XXX.XXX', 270...
This function implements the connection to mongoDB @returns connection (MongoClient or None) a MongoClient object to handle the connection. None on failure
This function implements the connection to mongoDB @returns connection (MongoClient or None) a MongoClient object to handle the connection. None on failure
[ "This", "function", "implements", "the", "connection", "to", "mongoDB", "@returns", "connection", "(", "MongoClient", "or", "None", ")", "a", "MongoClient", "object", "to", "handle", "the", "connection", ".", "None", "on", "failure" ]
def connect_to_mongodb(): try: connection = MongoClient('XXX.XXX.XXX.XXX', 27017) db = connection.admin db.authenticate('xxxxxx', 'xxxXXXxxxXX') return db except PyMongoError as e: print("Connection to Data Base failed: ", e) return None
[ "def", "connect_to_mongodb", "(", ")", ":", "try", ":", "connection", "=", "MongoClient", "(", "'XXX.XXX.XXX.XXX'", ",", "27017", ")", "db", "=", "connection", ".", "admin", "db", ".", "authenticate", "(", "'xxxxxx'", ",", "'xxxXXXxxxXX'", ")", "return", "db...
This function implements the connection to mongoDB @returns connection (MongoClient or None) a MongoClient object to handle the connection.
[ "This", "function", "implements", "the", "connection", "to", "mongoDB", "@returns", "connection", "(", "MongoClient", "or", "None", ")", "a", "MongoClient", "object", "to", "handle", "the", "connection", "." ]
[ "\"\"\" This function implements the connection to mongoDB\r\n @returns\r\n connection (MongoClient or None) a MongoClient object to handle the connection. None on failure\r\n \"\"\"", "# connect to database\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
073796e770e4aad6c6dec78adfd291a49c284243
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/malwaredomains.py
[ "MIT" ]
Python
crawl_malware_domains
<not_specific>
def crawl_malware_domains(url): """ This function crawls the malware domain indicator and returns all the dataset links to be downloaded and scraped later. @param url (string) url of the indicator web page @return """ print('Crawling site: ', url) downloader ...
This function crawls the malware domain indicator and returns all the dataset links to be downloaded and scraped later. @param url (string) url of the indicator web page @return
This function crawls the malware domain indicator and returns all the dataset links to be downloaded and scraped later. @param url (string) url of the indicator web page @return
[ "This", "function", "crawls", "the", "malware", "domain", "indicator", "and", "returns", "all", "the", "dataset", "links", "to", "be", "downloaded", "and", "scraped", "later", ".", "@param", "url", "(", "string", ")", "url", "of", "the", "indicator", "web", ...
def crawl_malware_domains(url): print('Crawling site: ', url) downloader = Downloader() print(url) html = downloader(url) soup = BeautifulSoup(html, 'html5lib') possible_links = soup.find_all('a') htmlLinks, htmlRemovedLinks = list([]), list([]) for link in possible_links : if li...
[ "def", "crawl_malware_domains", "(", "url", ")", ":", "print", "(", "'Crawling site: '", ",", "url", ")", "downloader", "=", "Downloader", "(", ")", "print", "(", "url", ")", "html", "=", "downloader", "(", "url", ")", "soup", "=", "BeautifulSoup", "(", ...
This function crawls the malware domain indicator and returns all the dataset links to be downloaded and scraped later.
[ "This", "function", "crawls", "the", "malware", "domain", "indicator", "and", "returns", "all", "the", "dataset", "links", "to", "be", "downloaded", "and", "scraped", "later", "." ]
[ "\"\"\" This function crawls the malware domain indicator and returns all the dataset links to be downloaded and scraped\r\n later.\r\n @param\r\n url (string) url of the indicator web page\r\n @return\r\n \"\"\"", "# construct full path using function parameter url = 'https://mi...
[ { "param": "url", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
41644ec4767521e1054058658c52e9a07f1b91c3
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/botscout_summer.py
[ "MIT" ]
Python
connect_to_mongodb
<not_specific>
def connect_to_mongodb(): """ This function implements the connection to the mongoDb :returns connection (MongoClient) a MongoClient object to handle the connection """ # connect to database connection = MongoClient('XXX.XXX.XXX.XXX', 27017) db = connection.admin ...
This function implements the connection to the mongoDb :returns connection (MongoClient) a MongoClient object to handle the connection
This function implements the connection to the mongoDb :returns connection (MongoClient) a MongoClient object to handle the connection
[ "This", "function", "implements", "the", "connection", "to", "the", "mongoDb", ":", "returns", "connection", "(", "MongoClient", ")", "a", "MongoClient", "object", "to", "handle", "the", "connection" ]
def connect_to_mongodb(): connection = MongoClient('XXX.XXX.XXX.XXX', 27017) db = connection.admin db.authenticate('xxxxxx', 'xxxXXXxxxXX') return db
[ "def", "connect_to_mongodb", "(", ")", ":", "connection", "=", "MongoClient", "(", "'XXX.XXX.XXX.XXX'", ",", "27017", ")", "db", "=", "connection", ".", "admin", "db", ".", "authenticate", "(", "'xxxxxx'", ",", "'xxxXXXxxxXX'", ")", "return", "db" ]
This function implements the connection to the mongoDb :returns connection (MongoClient) a MongoClient object to handle the connection
[ "This", "function", "implements", "the", "connection", "to", "the", "mongoDb", ":", "returns", "connection", "(", "MongoClient", ")", "a", "MongoClient", "object", "to", "handle", "the", "connection" ]
[ "\"\"\" This function implements the connection to the mongoDb\r\n :returns\r\n connection (MongoClient) a MongoClient object to handle the connection\r\n \"\"\"", "# connect to database\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
41644ec4767521e1054058658c52e9a07f1b91c3
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/botscout_summer.py
[ "MIT" ]
Python
scrape_it
<not_specific>
def scrape_it(html): """ Scrapes all the need data from the downloaded web page :parameter html (str) html source code (never None) of downloaded page :return values (list) list with all scraped values """ tree = fromstring(html) bot_entries = [...
Scrapes all the need data from the downloaded web page :parameter html (str) html source code (never None) of downloaded page :return values (list) list with all scraped values
Scrapes all the need data from the downloaded web page :parameter html (str) html source code (never None) of downloaded page :return values (list) list with all scraped values
[ "Scrapes", "all", "the", "need", "data", "from", "the", "downloaded", "web", "page", ":", "parameter", "html", "(", "str", ")", "html", "source", "code", "(", "never", "None", ")", "of", "downloaded", "page", ":", "return", "values", "(", "list", ")", ...
def scrape_it(html): tree = fromstring(html) bot_entries = [] content = tree.xpath('//td/text()')[6:] ip = tree.xpath('//td/a/text()') country = tree.xpath('//td/a/img/@title') num_rows = len(ip) for i in range(0, num_rows): position_of_entry = i*4 row = [ip[i]] + [country[i]...
[ "def", "scrape_it", "(", "html", ")", ":", "tree", "=", "fromstring", "(", "html", ")", "bot_entries", "=", "[", "]", "content", "=", "tree", ".", "xpath", "(", "'//td/text()'", ")", "[", "6", ":", "]", "ip", "=", "tree", ".", "xpath", "(", "'//td/...
Scrapes all the need data from the downloaded web page :parameter html (str) html source code (never None) of downloaded page :return values (list) list with all scraped values
[ "Scrapes", "all", "the", "need", "data", "from", "the", "downloaded", "web", "page", ":", "parameter", "html", "(", "str", ")", "html", "source", "code", "(", "never", "None", ")", "of", "downloaded", "page", ":", "return", "values", "(", "list", ")", ...
[ "\"\"\" Scrapes all the need data from the downloaded web page\r\n :parameter\r\n html (str) html source code (never None) of downloaded page\r\n :return\r\n values (list) list with all scraped values\r\n \"\"\"", "# print(i, position_of_entry, position_of_entry+1, po...
[ { "param": "html", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "html", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
41644ec4767521e1054058658c52e9a07f1b91c3
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/botscout_summer.py
[ "MIT" ]
Python
validate_and_enrich_time
<not_specific>
def validate_and_enrich_time(data_array): """ This function validates time goodies and returns them """ for row in data_array: date_string = row[3] datetime_obj = datetime.strptime(date_string, '%Y-%m-%d %I:%M %p') datetime_utc = fix_hour_utc(datetime_obj, +5) time...
This function validates time goodies and returns them
This function validates time goodies and returns them
[ "This", "function", "validates", "time", "goodies", "and", "returns", "them" ]
def validate_and_enrich_time(data_array): for row in data_array: date_string = row[3] datetime_obj = datetime.strptime(date_string, '%Y-%m-%d %I:%M %p') datetime_utc = fix_hour_utc(datetime_obj, +5) timestamp_utc = float(datetime_utc.timestamp()) datetime_utc_string = str(dat...
[ "def", "validate_and_enrich_time", "(", "data_array", ")", ":", "for", "row", "in", "data_array", ":", "date_string", "=", "row", "[", "3", "]", "datetime_obj", "=", "datetime", ".", "strptime", "(", "date_string", ",", "'%Y-%m-%d %I:%M %p'", ")", "datetime_utc"...
This function validates time goodies and returns them
[ "This", "function", "validates", "time", "goodies", "and", "returns", "them" ]
[ "\"\"\" This function validates time goodies and returns them\r\n \"\"\"" ]
[ { "param": "data_array", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data_array", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
12159c1a451c977a194b69fa8134c9c51fa35cdf
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/webBasedAttacks1.py
[ "MIT" ]
Python
model_as_json
<not_specific>
def model_as_json(html_values): """ This function processes splits information from the indicator and models it on dictionaries. @param html_values: (str or None) a string that contains scraped information @return ip_dict: (list) a list of dictionari...
This function processes splits information from the indicator and models it on dictionaries. @param html_values: (str or None) a string that contains scraped information @return ip_dict: (list) a list of dictionaries. Each contains an IP field
This function processes splits information from the indicator and models it on dictionaries. @param html_values: (str or None) a string that contains scraped information @return ip_dict: (list) a list of dictionaries. Each contains an IP field
[ "This", "function", "processes", "splits", "information", "from", "the", "indicator", "and", "models", "it", "on", "dictionaries", ".", "@param", "html_values", ":", "(", "str", "or", "None", ")", "a", "string", "that", "contains", "scraped", "information", "@...
def model_as_json(html_values): ip_dict = [] header = ["IP"] for ip_address in html_values.split('\n'): my_list = list([]) my_list.append(ip_address) ip_dict.append(dict(zip(header, my_list))) return ip_dict
[ "def", "model_as_json", "(", "html_values", ")", ":", "ip_dict", "=", "[", "]", "header", "=", "[", "\"IP\"", "]", "for", "ip_address", "in", "html_values", ".", "split", "(", "'\\n'", ")", ":", "my_list", "=", "list", "(", "[", "]", ")", "my_list", ...
This function processes splits information from the indicator and models it on dictionaries.
[ "This", "function", "processes", "splits", "information", "from", "the", "indicator", "and", "models", "it", "on", "dictionaries", "." ]
[ "\"\"\" This function processes splits information from the indicator and models it on dictionaries.\r\n @param\r\n html_values: (str or None) a string that contains scraped information\r\n @return\r\n ip_dict: (list) a list of dictionaries. Each contains an ...
[ { "param": "html_values", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "html_values", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
12159c1a451c977a194b69fa8134c9c51fa35cdf
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/webBasedAttacks1.py
[ "MIT" ]
Python
add_data
<not_specific>
def add_data(dict_list): """ Receives a list of dictionaries and add time of crawling related data. Then returns them back @param dict_list: (list) a list of dictionaries. Each contains an IP field @return dict_list: (list) a list of enriched data dictionaries "...
Receives a list of dictionaries and add time of crawling related data. Then returns them back @param dict_list: (list) a list of dictionaries. Each contains an IP field @return dict_list: (list) a list of enriched data dictionaries
Receives a list of dictionaries and add time of crawling related data. Then returns them back @param dict_list: (list) a list of dictionaries. Each contains an IP field @return dict_list: (list) a list of enriched data dictionaries
[ "Receives", "a", "list", "of", "dictionaries", "and", "add", "time", "of", "crawling", "related", "data", ".", "Then", "returns", "them", "back", "@param", "dict_list", ":", "(", "list", ")", "a", "list", "of", "dictionaries", ".", "Each", "contains", "an"...
def add_data(dict_list): for dict_entry in dict_list: datetime_utc_cti_string = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') datetime_utc_cti = datetime.strptime(datetime_utc_cti_string, '%Y-%m-%d %H:%M:%S') timestamp_utc_cti = datetime_utc_cti.timestamp() dict_entry["Category"] =...
[ "def", "add_data", "(", "dict_list", ")", ":", "for", "dict_entry", "in", "dict_list", ":", "datetime_utc_cti_string", "=", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", "datetime_utc_cti", "=", "datetime", ".", "strptime...
Receives a list of dictionaries and add time of crawling related data.
[ "Receives", "a", "list", "of", "dictionaries", "and", "add", "time", "of", "crawling", "related", "data", "." ]
[ "\"\"\" Receives a list of dictionaries and add time of crawling related data. Then returns them back\r\n @param\r\n dict_list: (list) a list of dictionaries. Each contains an IP field\r\n @return\r\n dict_list: (list) a list of enriched data dictionaries\r\n \"\"\"" ]
[ { "param": "dict_list", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "dict_list", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9b6bedb79e47c61a109abf2600e254884877a2f1
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/ipmasterlist_summer.py
[ "MIT" ]
Python
aggregate_content
<not_specific>
def aggregate_content(html_content): """ This function models html content into a dictionary form :param html_content (list) each item of this list is a string representation of a line from c2-ipmasterlist.txt :returns dict_list (list) this list contains the d...
This function models html content into a dictionary form :param html_content (list) each item of this list is a string representation of a line from c2-ipmasterlist.txt :returns dict_list (list) this list contains the dictionary representation of each html_content...
This function models html content into a dictionary form :param html_content (list) each item of this list is a string representation of a line from c2-ipmasterlist.txt :returns dict_list (list) this list contains the dictionary representation of each html_content line
[ "This", "function", "models", "html", "content", "into", "a", "dictionary", "form", ":", "param", "html_content", "(", "list", ")", "each", "item", "of", "this", "list", "is", "a", "string", "representation", "of", "a", "line", "from", "c2", "-", "ipmaster...
def aggregate_content(html_content): data_list = [] for line in html_content: if line == "": continue items = [word for word in line.split(',')] ip = items[0] ip_user = "" for word in items[1].split(): if word not in ["IP", "used", "by"]: ...
[ "def", "aggregate_content", "(", "html_content", ")", ":", "data_list", "=", "[", "]", "for", "line", "in", "html_content", ":", "if", "line", "==", "\"\"", ":", "continue", "items", "=", "[", "word", "for", "word", "in", "line", ".", "split", "(", "',...
This function models html content into a dictionary form :param html_content (list) each item of this list is a string representation of a line from c2-ipmasterlist.txt :returns dict_list (list) this list contains the dictionary representation of each html_content line
[ "This", "function", "models", "html", "content", "into", "a", "dictionary", "form", ":", "param", "html_content", "(", "list", ")", "each", "item", "of", "this", "list", "is", "a", "string", "representation", "of", "a", "line", "from", "c2", "-", "ipmaster...
[ "\"\"\" This function models html content into a dictionary form\r\n :param\r\n html_content (list) each item of this list is a string representation of a line from c2-ipmasterlist.txt\r\n :returns\r\n dict_list (list) this list contains the dictionary representation o...
[ { "param": "html_content", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "html_content", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c60c2a430bb6fd0765556715c127225ca659915b
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/today_limits_summer.py
[ "MIT" ]
Python
today_datetime
<not_specific>
def today_datetime(): """ This function returns the datetime limits of the current UTC date @returns today_start: (datetime) the first moment of current day today_end: (datetime) the last moment of current day """ str_now = datetime.utcnow().strftime('%Y-%m-...
This function returns the datetime limits of the current UTC date @returns today_start: (datetime) the first moment of current day today_end: (datetime) the last moment of current day
This function returns the datetime limits of the current UTC date
[ "This", "function", "returns", "the", "datetime", "limits", "of", "the", "current", "UTC", "date" ]
def today_datetime(): str_now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') now = datetime.strptime(str_now, '%Y-%m-%d %H:%M:%S').timetuple() today_start = datetime(now.tm_year, now.tm_mon, now.tm_mday, 0, 0, 0) today_end = datetime(now.tm_year, now.tm_mon, now.tm_mday, 23, 59, 59) return today_...
[ "def", "today_datetime", "(", ")", ":", "str_now", "=", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", "now", "=", "datetime", ".", "strptime", "(", "str_now", ",", "'%Y-%m-%d %H:%M:%S'", ")", ".", "timetuple", "(", ...
This function returns the datetime limits of the current UTC date
[ "This", "function", "returns", "the", "datetime", "limits", "of", "the", "current", "UTC", "date" ]
[ "\"\"\" This function returns the datetime limits of the current UTC date\r\n @returns\r\n today_start: (datetime) the first moment of current day\r\n today_end: (datetime) the last moment of current day\r\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "returns", "docstring": "(datetime) the first moment of current day\ntoday_end: (datetime) the last moment of current day", "docstring_tokens": [ "(", "datetime", ...
d68bbf9c04aba24cc324ce0974f372f3e1065d24
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/descriptive_analysis.py
[ "MIT" ]
Python
time_series_analysis
<not_specific>
def time_series_analysis(results_cursor, mongo_date_type='mongoDate', entity_type=None): """ Given a cursor that contains a query result set, this function performs time series analysis and returns the result data frame. @parameters results_cursor (cursor) pymongo's result cu...
Given a cursor that contains a query result set, this function performs time series analysis and returns the result data frame. @parameters results_cursor (cursor) pymongo's result cursor. It is returned by a query mongo_date_type (str) this parameter sets ...
Given a cursor that contains a query result set, this function performs time series analysis and returns the result data frame. @parameters results_cursor (cursor) pymongo's result cursor. It is returned by a query mongo_date_type (str) this parameter sets the datetime object based on which will take ...
[ "Given", "a", "cursor", "that", "contains", "a", "query", "result", "set", "this", "function", "performs", "time", "series", "analysis", "and", "returns", "the", "result", "data", "frame", ".", "@parameters", "results_cursor", "(", "cursor", ")", "pymongo", "'...
def time_series_analysis(results_cursor, mongo_date_type='mongoDate', entity_type=None): print("\nBegin Descriptive Analysis Phase... ", end='') if results_cursor.count() == 0: try: raise Warning("No documents retrieved") except Exception as e: print("\ndescriptive_analys...
[ "def", "time_series_analysis", "(", "results_cursor", ",", "mongo_date_type", "=", "'mongoDate'", ",", "entity_type", "=", "None", ")", ":", "print", "(", "\"\\nBegin Descriptive Analysis Phase... \"", ",", "end", "=", "''", ")", "if", "results_cursor", ".", "count"...
Given a cursor that contains a query result set, this function performs time series analysis and returns the result data frame.
[ "Given", "a", "cursor", "that", "contains", "a", "query", "result", "set", "this", "function", "performs", "time", "series", "analysis", "and", "returns", "the", "result", "data", "frame", "." ]
[ "\"\"\" Given a cursor that contains a query result set, this function performs time series analysis and returns\r\n the result data frame.\r\n @parameters\r\n results_cursor (cursor) pymongo's result cursor. It is returned by a query\r\n mongo_date_type (str) t...
[ { "param": "results_cursor", "type": null }, { "param": "mongo_date_type", "type": null }, { "param": "entity_type", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "results_cursor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mongo_date_type", "type": null, "docstring": null, ...
d68bbf9c04aba24cc324ce0974f372f3e1065d24
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/descriptive_analysis.py
[ "MIT" ]
Python
time_series_analysis_per_month
<not_specific>
def time_series_analysis_per_month(results_cursor, mongo_date_type='mongoDate', entity_type=None): """ Given a cursor that contains a query result set, this function performs time series analysis and returns the result data frame for analysed number of attacks per month. @parameters ...
Given a cursor that contains a query result set, this function performs time series analysis and returns the result data frame for analysed number of attacks per month. @parameters results_cursor (cursor) pymongo's result cursor. It is returned by a query mongo_date_...
Given a cursor that contains a query result set, this function performs time series analysis and returns the result data frame for analysed number of attacks per month. @parameters results_cursor (cursor) pymongo's result cursor. It is returned by a query mongo_date_type (str) this parameter sets the ...
[ "Given", "a", "cursor", "that", "contains", "a", "query", "result", "set", "this", "function", "performs", "time", "series", "analysis", "and", "returns", "the", "result", "data", "frame", "for", "analysed", "number", "of", "attacks", "per", "month", ".", "@...
def time_series_analysis_per_month(results_cursor, mongo_date_type='mongoDate', entity_type=None): print("\nBegin Descriptive Analysis Phase... ", end='') if results_cursor.count() == 0: try: raise Warning("No documents retrieved") except Exception as e: print("\ndescript...
[ "def", "time_series_analysis_per_month", "(", "results_cursor", ",", "mongo_date_type", "=", "'mongoDate'", ",", "entity_type", "=", "None", ")", ":", "print", "(", "\"\\nBegin Descriptive Analysis Phase... \"", ",", "end", "=", "''", ")", "if", "results_cursor", ".",...
Given a cursor that contains a query result set, this function performs time series analysis and returns the result data frame for analysed number of attacks per month.
[ "Given", "a", "cursor", "that", "contains", "a", "query", "result", "set", "this", "function", "performs", "time", "series", "analysis", "and", "returns", "the", "result", "data", "frame", "for", "analysed", "number", "of", "attacks", "per", "month", "." ]
[ "\"\"\" Given a cursor that contains a query result set, this function performs time series analysis and returns\r\n the result data frame for analysed number of attacks per month.\r\n @parameters\r\n results_cursor (cursor) pymongo's result cursor. It is returned by a query\r\n ...
[ { "param": "results_cursor", "type": null }, { "param": "mongo_date_type", "type": null }, { "param": "entity_type", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "results_cursor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mongo_date_type", "type": null, "docstring": null, ...
d68bbf9c04aba24cc324ce0974f372f3e1065d24
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/descriptive_analysis.py
[ "MIT" ]
Python
update_time_series_analysis_files
<not_specific>
def update_time_series_analysis_files(attacks_data_frame, analysis_file_name, path): """ This function transforms data from two different sources and combines them to produce a merged result. This result is then saved in a file. The first source is attacks data_frame (contains one or more data frames) tha...
This function transforms data from two different sources and combines them to produce a merged result. This result is then saved in a file. The first source is attacks data_frame (contains one or more data frames) that gets transformed into a dictionary. The second source is the analysis_file_name.JS...
This function transforms data from two different sources and combines them to produce a merged result. This result is then saved in a file. The first source is attacks data_frame (contains one or more data frames) that gets transformed into a dictionary. The second source is the analysis_file_name.JSON that gets tranfo...
[ "This", "function", "transforms", "data", "from", "two", "different", "sources", "and", "combines", "them", "to", "produce", "a", "merged", "result", ".", "This", "result", "is", "then", "saved", "in", "a", "file", ".", "The", "first", "source", "is", "att...
def update_time_series_analysis_files(attacks_data_frame, analysis_file_name, path): if attacks_data_frame.empty: try: raise Warning("No documents in cursor to be written") except Exception as e: print("descriptive_analysis module > update_time_series_analysis_files: ", e) ...
[ "def", "update_time_series_analysis_files", "(", "attacks_data_frame", ",", "analysis_file_name", ",", "path", ")", ":", "if", "attacks_data_frame", ".", "empty", ":", "try", ":", "raise", "Warning", "(", "\"No documents in cursor to be written\"", ")", "except", "Excep...
This function transforms data from two different sources and combines them to produce a merged result.
[ "This", "function", "transforms", "data", "from", "two", "different", "sources", "and", "combines", "them", "to", "produce", "a", "merged", "result", "." ]
[ "\"\"\" This function transforms data from two different sources and combines them to produce a merged result. This\r\n result is then saved in a file. The first source is attacks data_frame (contains one or more data frames) that\r\n gets transformed into a dictionary. The second source is the analys...
[ { "param": "attacks_data_frame", "type": null }, { "param": "analysis_file_name", "type": null }, { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "attacks_data_frame", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "analysis_file_name", "type": null, "docstring": null,...
d68bbf9c04aba24cc324ce0974f372f3e1065d24
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/descriptive_analysis.py
[ "MIT" ]
Python
top_n
<not_specific>
def top_n(results_cursor, n, key, barplot_file_name, path): """ It calculates the frequency of appearance for values of a given key in query result. Then returns the top n most common values with the number of appearance. This result gets stored in json and csv files but also gets returned by the...
It calculates the frequency of appearance for values of a given key in query result. Then returns the top n most common values with the number of appearance. This result gets stored in json and csv files but also gets returned by the function. @parameters dataset_name (st...
It calculates the frequency of appearance for values of a given key in query result. Then returns the top n most common values with the number of appearance. This result gets stored in json and csv files but also gets returned by the function.
[ "It", "calculates", "the", "frequency", "of", "appearance", "for", "values", "of", "a", "given", "key", "in", "query", "result", ".", "Then", "returns", "the", "top", "n", "most", "common", "values", "with", "the", "number", "of", "appearance", ".", "This"...
def top_n(results_cursor, n, key, barplot_file_name, path): type_of_attacks = list([]) try: for doc in results_cursor.rewind(): type_of_attacks.append(doc[key]) results = Counter(type_of_attacks).most_common(n) highcharts_results = list([]) for result in results: ...
[ "def", "top_n", "(", "results_cursor", ",", "n", ",", "key", ",", "barplot_file_name", ",", "path", ")", ":", "type_of_attacks", "=", "list", "(", "[", "]", ")", "try", ":", "for", "doc", "in", "results_cursor", ".", "rewind", "(", ")", ":", "type_of_a...
It calculates the frequency of appearance for values of a given key in query result.
[ "It", "calculates", "the", "frequency", "of", "appearance", "for", "values", "of", "a", "given", "key", "in", "query", "result", "." ]
[ "\"\"\" It calculates the frequency of appearance for values of a given key in query result.\r\n Then returns the top n most common values with the number of appearance.\r\n This result gets stored in json and csv files but also gets returned by the function.\r\n @parameters\r\n data...
[ { "param": "results_cursor", "type": null }, { "param": "n", "type": null }, { "param": "key", "type": null }, { "param": "barplot_file_name", "type": null }, { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "results_cursor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "n", "type": null, "docstring": null, "docstring_tok...
d68bbf9c04aba24cc324ce0974f372f3e1065d24
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/descriptive_analysis.py
[ "MIT" ]
Python
today_datetime
<not_specific>
def today_datetime(utc_now): """ This function returns the datetime limits for a given UTC datetime @parameters utc_now (datetime) the datetime to be based on @returns today_start: (datetime) the first moment of current day today_end: (date...
This function returns the datetime limits for a given UTC datetime @parameters utc_now (datetime) the datetime to be based on @returns today_start: (datetime) the first moment of current day today_end: (datetime) the last moment of current day...
This function returns the datetime limits for a given UTC datetime @parameters utc_now (datetime) the datetime to be based on @returns today_start: (datetime) the first moment of current day today_end: (datetime) the last moment of current day
[ "This", "function", "returns", "the", "datetime", "limits", "for", "a", "given", "UTC", "datetime", "@parameters", "utc_now", "(", "datetime", ")", "the", "datetime", "to", "be", "based", "on", "@returns", "today_start", ":", "(", "datetime", ")", "the", "fi...
def today_datetime(utc_now): today_start = datetime(utc_now.year, utc_now.month, utc_now.day, 0, 0, 0) today_end = datetime(utc_now.year, utc_now.month, utc_now.day, 23, 59, 59) return today_start, today_end
[ "def", "today_datetime", "(", "utc_now", ")", ":", "today_start", "=", "datetime", "(", "utc_now", ".", "year", ",", "utc_now", ".", "month", ",", "utc_now", ".", "day", ",", "0", ",", "0", ",", "0", ")", "today_end", "=", "datetime", "(", "utc_now", ...
This function returns the datetime limits for a given UTC datetime @parameters utc_now (datetime) the datetime to be based on @returns today_start: (datetime) the first moment of current day today_end: (datetime) the last moment of current day
[ "This", "function", "returns", "the", "datetime", "limits", "for", "a", "given", "UTC", "datetime", "@parameters", "utc_now", "(", "datetime", ")", "the", "datetime", "to", "be", "based", "on", "@returns", "today_start", ":", "(", "datetime", ")", "the", "fi...
[ "\"\"\" This function returns the datetime limits for a given UTC datetime\r\n @parameters\r\n utc_now (datetime) the datetime to be based on\r\n @returns\r\n today_start: (datetime) the first moment of current day\r\n today_end: (datetime) the last ...
[ { "param": "utc_now", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "utc_now", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7595f1561b6bf44e15df214a1e4804d086330e9d
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/downloader_phishing.py
[ "MIT" ]
Python
download
<not_specific>
def download(self, url, user_agent, num_tries=2, charset='utf-8'): """ This function downloads a website's source code. @parameters url: (str) website's url user_agent: (str) specifies the user_agent string num_tries: (...
This function downloads a website's source code. @parameters url: (str) website's url user_agent: (str) specifies the user_agent string num_tries: (int) if a download fails due to a problem with the request (4xx) or t...
This function downloads a website's source code.
[ "This", "function", "downloads", "a", "website", "'", "s", "source", "code", "." ]
def download(self, url, user_agent, num_tries=2, charset='utf-8'): print("Downloading %s ... " % url) request = urllib.request.Request(url) request.add_header('User-Agent', user_agent) try: if self.proxy: proxy_support = urllib.request.ProxyHandler({'http': se...
[ "def", "download", "(", "self", ",", "url", ",", "user_agent", ",", "num_tries", "=", "2", ",", "charset", "=", "'utf-8'", ")", ":", "print", "(", "\"Downloading %s ... \"", "%", "url", ")", "request", "=", "urllib", ".", "request", ".", "Request", "(", ...
This function downloads a website's source code.
[ "This", "function", "downloads", "a", "website", "'", "s", "source", "code", "." ]
[ "\"\"\" This function downloads a website's source code.\r\n @parameters\r\n url: (str) website's url\r\n user_agent: (str) specifies the user_agent string\r\n num_tries: (int) if a download fails due to a problem with the...
[ { "param": "self", "type": null }, { "param": "url", "type": null }, { "param": "user_agent", "type": null }, { "param": "num_tries", "type": null }, { "param": "charset", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": []...
d2995d404e10f0d9b03d7325832f4d6b3e3baf2a
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/ipmasterlist.py
[ "MIT" ]
Python
aggregate_content
<not_specific>
def aggregate_content(html_content): """ This function models html content into a dictionary form @param html_content (list) each item of this list is a string representation of a line from c2-ipmasterlist.txt @returns dict_list (list) this list contains the d...
This function models html content into a dictionary form @param html_content (list) each item of this list is a string representation of a line from c2-ipmasterlist.txt @returns dict_list (list) this list contains the dictionary representation of each html_content...
This function models html content into a dictionary form @param html_content (list) each item of this list is a string representation of a line from c2-ipmasterlist.txt @returns dict_list (list) this list contains the dictionary representation of each html_content line
[ "This", "function", "models", "html", "content", "into", "a", "dictionary", "form", "@param", "html_content", "(", "list", ")", "each", "item", "of", "this", "list", "is", "a", "string", "representation", "of", "a", "line", "from", "c2", "-", "ipmasterlist",...
def aggregate_content(html_content): data_list = [] for line in html_content: if line == "": continue items = [word for word in line.split(',')] ip = items[0] ip_user = "" for word in items[1].split(): if word not in ["IP", "used", "by"]: ...
[ "def", "aggregate_content", "(", "html_content", ")", ":", "data_list", "=", "[", "]", "for", "line", "in", "html_content", ":", "if", "line", "==", "\"\"", ":", "continue", "items", "=", "[", "word", "for", "word", "in", "line", ".", "split", "(", "',...
This function models html content into a dictionary form @param html_content (list) each item of this list is a string representation of a line from c2-ipmasterlist.txt @returns dict_list (list) this list contains the dictionary representation of each html_content line
[ "This", "function", "models", "html", "content", "into", "a", "dictionary", "form", "@param", "html_content", "(", "list", ")", "each", "item", "of", "this", "list", "is", "a", "string", "representation", "of", "a", "line", "from", "c2", "-", "ipmasterlist",...
[ "\"\"\" This function models html content into a dictionary form\r\n @param\r\n html_content (list) each item of this list is a string representation of a line from c2-ipmasterlist.txt\r\n @returns\r\n dict_list (list) this list contains the dictionary representation o...
[ { "param": "html_content", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "html_content", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
eeead7be5ce51a58ec490d324d92b3bfa829abd0
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/markets/hackerone.py
[ "MIT" ]
Python
high_charts_timestamp
<not_specific>
def high_charts_timestamp(datetime_obj): """ This is a post processing function. It receives a pandas datetime element and takes care of producing a timestamp suitable for high charts library. @parameters datetime_obj (datetime) @returns __high_charts_t...
This is a post processing function. It receives a pandas datetime element and takes care of producing a timestamp suitable for high charts library. @parameters datetime_obj (datetime) @returns __high_charts_timestamp__ (timestamp) readable by high ch...
This is a post processing function. It receives a pandas datetime element and takes care of producing a timestamp suitable for high charts library. @parameters datetime_obj (datetime) @returns high_charts_timestamp__ (timestamp) readable by high charts library
[ "This", "is", "a", "post", "processing", "function", ".", "It", "receives", "a", "pandas", "datetime", "element", "and", "takes", "care", "of", "producing", "a", "timestamp", "suitable", "for", "high", "charts", "library", ".", "@parameters", "datetime_obj", "...
def high_charts_timestamp(datetime_obj): datetime_obj_tuple = datetime_obj.timetuple() year = datetime_obj_tuple.tm_year month = datetime_obj_tuple.tm_mon day = datetime_obj_tuple.tm_mday high_charts_datetime_string = datetime(year, month, day, 14, 0, 0, 0).strftime('%Y-%m-%d %H:%M:%S.%f') high_...
[ "def", "high_charts_timestamp", "(", "datetime_obj", ")", ":", "datetime_obj_tuple", "=", "datetime_obj", ".", "timetuple", "(", ")", "year", "=", "datetime_obj_tuple", ".", "tm_year", "month", "=", "datetime_obj_tuple", ".", "tm_mon", "day", "=", "datetime_obj_tupl...
This is a post processing function.
[ "This", "is", "a", "post", "processing", "function", "." ]
[ "\"\"\" This is a post processing function. It receives a pandas datetime element and takes care of producing\n a timestamp suitable for high charts library.\n @parameters\n datetime_obj (datetime)\n @returns\n __high_charts_timestamp__ (timestamp) rea...
[ { "param": "datetime_obj", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "datetime_obj", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6fd869f51d2c79265139c45b87495dcb04023cfc
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/phishtank-alev.py
[ "MIT" ]
Python
data_frame_to_json
null
def data_frame_to_json(data_frame, filename): """ Given a data_frame creates a list of smaller lists that contain data frame pairs and stores them in a json file @param data_frame filename: (str) the name of the json file to be created """ data_frame_list = list([...
Given a data_frame creates a list of smaller lists that contain data frame pairs and stores them in a json file @param data_frame filename: (str) the name of the json file to be created
Given a data_frame creates a list of smaller lists that contain data frame pairs and stores them in a json file @param data_frame filename: (str) the name of the json file to be created
[ "Given", "a", "data_frame", "creates", "a", "list", "of", "smaller", "lists", "that", "contain", "data", "frame", "pairs", "and", "stores", "them", "in", "a", "json", "file", "@param", "data_frame", "filename", ":", "(", "str", ")", "the", "name", "of", ...
def data_frame_to_json(data_frame, filename): data_frame_list = list([]) for row in data_frame.itertuples(): timestamp = high_charts_timestamp(row[0]) row_list = [timestamp, row[1]] data_frame_list.append(row_list) with open(filename, 'w') as json_file: json.dump(data_frame_l...
[ "def", "data_frame_to_json", "(", "data_frame", ",", "filename", ")", ":", "data_frame_list", "=", "list", "(", "[", "]", ")", "for", "row", "in", "data_frame", ".", "itertuples", "(", ")", ":", "timestamp", "=", "high_charts_timestamp", "(", "row", "[", "...
Given a data_frame creates a list of smaller lists that contain data frame pairs and stores them in a json file @param data_frame filename: (str) the name of the json file to be created
[ "Given", "a", "data_frame", "creates", "a", "list", "of", "smaller", "lists", "that", "contain", "data", "frame", "pairs", "and", "stores", "them", "in", "a", "json", "file", "@param", "data_frame", "filename", ":", "(", "str", ")", "the", "name", "of", ...
[ "\"\"\" Given a data_frame creates a list of smaller lists that contain data frame pairs and stores them in a json file\r\n @param\r\n data_frame\r\n filename: (str) the name of the json file to be created\r\n \"\"\"", "# break down every data frame row in tuple\r", "# then k...
[ { "param": "data_frame", "type": null }, { "param": "filename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data_frame", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "filename", "type": null, "docstring": null, "docstring_...
6fd869f51d2c79265139c45b87495dcb04023cfc
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/phishtank-alev.py
[ "MIT" ]
Python
time_series_analysis
null
def time_series_analysis(db): """ Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts) @param db: (Mongo Client) this is the connection...
Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts) @param db: (Mongo Client) this is the connection returned by Pymongo Client, ...
Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts)
[ "Collects", "all", "the", "information", "from", "the", "collection", "and", "presents", "the", "number", "of", "blocked", "IP", "'", "s", "per", "day", "Saves", "the", "results", "in", "csv", "and", "json", "file", "respectively", "for", "later", "process",...
def time_series_analysis(db): num_of_docs_in_collection = db.threats.phishtank.count() if num_of_docs_in_collection != 0: try: cursor = db.threats.phishtank.find({}, {'mongoDate': 1, '_id': 0}) dates_list = list([]) for doc in cursor: dates_list.append...
[ "def", "time_series_analysis", "(", "db", ")", ":", "num_of_docs_in_collection", "=", "db", ".", "threats", ".", "phishtank", ".", "count", "(", ")", "if", "num_of_docs_in_collection", "!=", "0", ":", "try", ":", "cursor", "=", "db", ".", "threats", ".", "...
Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts)
[ "Collects", "all", "the", "information", "from", "the", "collection", "and", "presents", "the", "number", "of", "blocked", "IP", "'", "s", "per", "day", "Saves", "the", "results", "in", "csv", "and", "json", "file", "respectively", "for", "later", "process",...
[ "\"\"\" Collects all the information from the collection and presents the number of blocked IP's per day\r\n Saves the results in csv and json file respectively for later process (stakeholders and Highcharts)\r\n @param\r\n db: (Mongo Client) this is the connection returned by Pymongo ...
[ { "param": "db", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "db", "type": null, "docstring": "(Mongo Client) this is the connection returned by Pymongo Client,\nwe take it from connect_to_mongodb() function", "docstring_tokens": [ "(", "Mongo", "Client", ...
6fd869f51d2c79265139c45b87495dcb04023cfc
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/phishtank-alev.py
[ "MIT" ]
Python
extract_collection_copy
null
def extract_collection_copy(db): """ For a given data base, retrieves all data from a collection and export them in json and csv files @param db: (Mongo Client) this is the connection returned by Pymongo Client, we take it from connect_to_mongodb() fu...
For a given data base, retrieves all data from a collection and export them in json and csv files @param db: (Mongo Client) this is the connection returned by Pymongo Client, we take it from connect_to_mongodb() function
For a given data base, retrieves all data from a collection and export them in json and csv files
[ "For", "a", "given", "data", "base", "retrieves", "all", "data", "from", "a", "collection", "and", "export", "them", "in", "json", "and", "csv", "files" ]
def extract_collection_copy(db): json_filename = server_path + 'dataset-phishing.json' csv_filename = server_path + 'dataset-phishing.csv' try: cursor = db.threats.phishtank.find({}, {"_id": 0, "mongoDate": 0, "mongoDate-CTI": 0}) with open(json_filename, 'w') as json_file: json_...
[ "def", "extract_collection_copy", "(", "db", ")", ":", "json_filename", "=", "server_path", "+", "'dataset-phishing.json'", "csv_filename", "=", "server_path", "+", "'dataset-phishing.csv'", "try", ":", "cursor", "=", "db", ".", "threats", ".", "phishtank", ".", "...
For a given data base, retrieves all data from a collection and export them in json and csv files
[ "For", "a", "given", "data", "base", "retrieves", "all", "data", "from", "a", "collection", "and", "export", "them", "in", "json", "and", "csv", "files" ]
[ "\"\"\" For a given data base, retrieves all data from a collection and export them in json and csv files\r\n @param\r\n db: (Mongo Client) this is the connection returned by Pymongo Client,\r\n we take it from connect_to_mongodb() function\r\n \"\"\"", ...
[ { "param": "db", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "db", "type": null, "docstring": "(Mongo Client) this is the connection returned by Pymongo Client,\nwe take it from connect_to_mongodb() function", "docstring_tokens": [ "(", "Mongo", "Client", ...
13ad2687a7383043b7faa6fcb80534a313ac523f
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/botscout.py
[ "MIT" ]
Python
scrape_it
<not_specific>
def scrape_it(html_code): """ Scrapes all the need data from the downloaded web page @parameter html_code (str) html source code (never None) of downloaded page @return bot_entries (list) list of all scraped values """ tree = fromstring(html_code) ...
Scrapes all the need data from the downloaded web page @parameter html_code (str) html source code (never None) of downloaded page @return bot_entries (list) list of all scraped values
Scrapes all the need data from the downloaded web page @parameter html_code (str) html source code (never None) of downloaded page @return bot_entries (list) list of all scraped values
[ "Scrapes", "all", "the", "need", "data", "from", "the", "downloaded", "web", "page", "@parameter", "html_code", "(", "str", ")", "html", "source", "code", "(", "never", "None", ")", "of", "downloaded", "page", "@return", "bot_entries", "(", "list", ")", "l...
def scrape_it(html_code): tree = fromstring(html_code) bot_entries = [] content = tree.xpath('//td/text()')[6:] ip = tree.xpath('//td/a/text()') country = tree.xpath('//td/a/img/@title') num_rows = len(ip) for i in range(0, num_rows): position_of_entry = i*4 row = [ip[i]] + [...
[ "def", "scrape_it", "(", "html_code", ")", ":", "tree", "=", "fromstring", "(", "html_code", ")", "bot_entries", "=", "[", "]", "content", "=", "tree", ".", "xpath", "(", "'//td/text()'", ")", "[", "6", ":", "]", "ip", "=", "tree", ".", "xpath", "(",...
Scrapes all the need data from the downloaded web page @parameter html_code (str) html source code (never None) of downloaded page @return bot_entries (list) list of all scraped values
[ "Scrapes", "all", "the", "need", "data", "from", "the", "downloaded", "web", "page", "@parameter", "html_code", "(", "str", ")", "html", "source", "code", "(", "never", "None", ")", "of", "downloaded", "page", "@return", "bot_entries", "(", "list", ")", "l...
[ "\"\"\" Scrapes all the need data from the downloaded web page\r\n @parameter\r\n html_code (str) html source code (never None) of downloaded page\r\n @return\r\n bot_entries (list) list of all scraped values\r\n \"\"\"", "# print(i, position_of_entry, position_of_ent...
[ { "param": "html_code", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "html_code", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
13ad2687a7383043b7faa6fcb80534a313ac523f
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/botscout.py
[ "MIT" ]
Python
validate_time
<not_specific>
def validate_time(data_array): """ This function validates time goodies and returns them @parameter data_array (list) a list of sub-lists. Each sublist contains bot entries @returns data_array (list) a list of sub-lists. Each sublist contains VALIDATED bot entries ...
This function validates time goodies and returns them @parameter data_array (list) a list of sub-lists. Each sublist contains bot entries @returns data_array (list) a list of sub-lists. Each sublist contains VALIDATED bot entries
This function validates time goodies and returns them @parameter data_array (list) a list of sub-lists. Each sublist contains bot entries @returns data_array (list) a list of sub-lists. Each sublist contains VALIDATED bot entries
[ "This", "function", "validates", "time", "goodies", "and", "returns", "them", "@parameter", "data_array", "(", "list", ")", "a", "list", "of", "sub", "-", "lists", ".", "Each", "sublist", "contains", "bot", "entries", "@returns", "data_array", "(", "list", "...
def validate_time(data_array): for row in data_array: date_string = row[3] datetime_obj = datetime.strptime(date_string, '%Y-%m-%d %I:%M %p') datetime_utc = fix_hour_utc(datetime_obj, +5) timestamp_utc = float(datetime_utc.timestamp()) datetime_utc_string = str(datetime_utc) ...
[ "def", "validate_time", "(", "data_array", ")", ":", "for", "row", "in", "data_array", ":", "date_string", "=", "row", "[", "3", "]", "datetime_obj", "=", "datetime", ".", "strptime", "(", "date_string", ",", "'%Y-%m-%d %I:%M %p'", ")", "datetime_utc", "=", ...
This function validates time goodies and returns them @parameter data_array (list) a list of sub-lists.
[ "This", "function", "validates", "time", "goodies", "and", "returns", "them", "@parameter", "data_array", "(", "list", ")", "a", "list", "of", "sub", "-", "lists", "." ]
[ "\"\"\" This function validates time goodies and returns them\r\n @parameter\r\n data_array (list) a list of sub-lists. Each sublist contains bot entries\r\n @returns\r\n data_array (list) a list of sub-lists. Each sublist contains VALIDATED bot entries\r\n \"\"\"" ]
[ { "param": "data_array", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data_array", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
13ad2687a7383043b7faa6fcb80534a313ac523f
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/botscout.py
[ "MIT" ]
Python
fix_hour_utc
<not_specific>
def fix_hour_utc(datetime_obj, hour_interval): """ This function adds some hours in a datetime object @param datetime_obj (datetime) hour_interval (int) represents the hours to add @returns a new datetime time object """ return datetime_obj + timedelta(hour...
This function adds some hours in a datetime object @param datetime_obj (datetime) hour_interval (int) represents the hours to add @returns a new datetime time object
This function adds some hours in a datetime object @param datetime_obj (datetime) hour_interval (int) represents the hours to add @returns a new datetime time object
[ "This", "function", "adds", "some", "hours", "in", "a", "datetime", "object", "@param", "datetime_obj", "(", "datetime", ")", "hour_interval", "(", "int", ")", "represents", "the", "hours", "to", "add", "@returns", "a", "new", "datetime", "time", "object" ]
def fix_hour_utc(datetime_obj, hour_interval): return datetime_obj + timedelta(hours=hour_interval)
[ "def", "fix_hour_utc", "(", "datetime_obj", ",", "hour_interval", ")", ":", "return", "datetime_obj", "+", "timedelta", "(", "hours", "=", "hour_interval", ")" ]
This function adds some hours in a datetime object @param datetime_obj (datetime) hour_interval (int) represents the hours to add @returns a new datetime time object
[ "This", "function", "adds", "some", "hours", "in", "a", "datetime", "object", "@param", "datetime_obj", "(", "datetime", ")", "hour_interval", "(", "int", ")", "represents", "the", "hours", "to", "add", "@returns", "a", "new", "datetime", "time", "object" ]
[ "\"\"\" This function adds some hours in a datetime object\r\n @param\r\n datetime_obj (datetime)\r\n hour_interval (int) represents the hours to add\r\n @returns\r\n a new datetime time object\r\n \"\"\"" ]
[ { "param": "datetime_obj", "type": null }, { "param": "hour_interval", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "datetime_obj", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "hour_interval", "type": null, "docstring": null, "doc...
13ad2687a7383043b7faa6fcb80534a313ac523f
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/botscout.py
[ "MIT" ]
Python
model_as_json
<not_specific>
def model_as_json(bot_entries): """ Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB @param bot_entries (list) list of sub-lists @returns json_list (list) list of modeled dictionaries ...
Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB @param bot_entries (list) list of sub-lists @returns json_list (list) list of modeled dictionaries
Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB @param bot_entries (list) list of sub-lists @returns json_list (list) list of modeled dictionaries
[ "Casts", "a", "list", "of", "lists", "into", "a", "list", "of", "modeled", "dictionaries", ".", "New", "data", "format", "is", "JSON", "-", "like", "and", "suitable", "for", "MongoDB", "@param", "bot_entries", "(", "list", ")", "list", "of", "sub", "-", ...
def model_as_json(bot_entries): json_list = [] for bot_entry in bot_entries: json_object = { "_id": bot_entry[2], "Category": "Botnets", "Entity-Type": "IP", "IP": bot_entry[0], "Botscout-id": bot_entry[2], "Bot-Name": bot_entry[4],...
[ "def", "model_as_json", "(", "bot_entries", ")", ":", "json_list", "=", "[", "]", "for", "bot_entry", "in", "bot_entries", ":", "json_object", "=", "{", "\"_id\"", ":", "bot_entry", "[", "2", "]", ",", "\"Category\"", ":", "\"Botnets\"", ",", "\"Entity-Type\...
Casts a list of lists into a list of modeled dictionaries.
[ "Casts", "a", "list", "of", "lists", "into", "a", "list", "of", "modeled", "dictionaries", "." ]
[ "\"\"\" Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB\r\n @param\r\n bot_entries (list) list of sub-lists\r\n @returns\r\n json_list (list) list of modeled dictionaries\r\n \"\"\"" ]
[ { "param": "bot_entries", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "bot_entries", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e545a0d58cb10e1bf39a5813d17cf3f91730c288
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/ransomware.py
[ "MIT" ]
Python
crawl_ransomware_lists
<not_specific>
def crawl_ransomware_lists(html_code): """ Scrapes all the need data from the downloaded web page @parameter html (str) html source code (never None) of downloaded page @retukrn values (list) list with all scraped values """ soup = BeautifulSoup(html_c...
Scrapes all the need data from the downloaded web page @parameter html (str) html source code (never None) of downloaded page @retukrn values (list) list with all scraped values
Scrapes all the need data from the downloaded web page @parameter html (str) html source code (never None) of downloaded page @retukrn values (list) list with all scraped values
[ "Scrapes", "all", "the", "need", "data", "from", "the", "downloaded", "web", "page", "@parameter", "html", "(", "str", ")", "html", "source", "code", "(", "never", "None", ")", "of", "downloaded", "page", "@retukrn", "values", "(", "list", ")", "list", "...
def crawl_ransomware_lists(html_code): soup = BeautifulSoup(html_code, 'lxml') second_table_rows = soup.find_all('table')[1] td_elements = second_table_rows.find_all('td') block_lists = list([]) for i in range(0, len(td_elements), 6): try: relative_link = td_elements[i+5].a.get('...
[ "def", "crawl_ransomware_lists", "(", "html_code", ")", ":", "soup", "=", "BeautifulSoup", "(", "html_code", ",", "'lxml'", ")", "second_table_rows", "=", "soup", ".", "find_all", "(", "'table'", ")", "[", "1", "]", "td_elements", "=", "second_table_rows", "."...
Scrapes all the need data from the downloaded web page @parameter html (str) html source code (never None) of downloaded page @retukrn values (list) list with all scraped values
[ "Scrapes", "all", "the", "need", "data", "from", "the", "downloaded", "web", "page", "@parameter", "html", "(", "str", ")", "html", "source", "code", "(", "never", "None", ")", "of", "downloaded", "page", "@retukrn", "values", "(", "list", ")", "list", "...
[ "\"\"\" Scrapes all the need data from the downloaded web page\r\n @parameter\r\n html (str) html source code (never None) of downloaded page\r\n @retukrn\r\n values (list) list with all scraped values\r\n \"\"\"", "# row_list.append(td_elements[i].string)\r", "# --...
[ { "param": "html_code", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "html_code", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
79aa262355c036d092f52b91ef88aaea2ffc1458
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/threats_monitoring/downloader_ransomware.py
[ "MIT" ]
Python
download
<not_specific>
def download(self, url, user_agent, num_retries): """ This function downloads a website's source code. @parameters url (str) website's url user_agent (str) specifies the user_agent string num_retries (int) if...
This function downloads a website's source code. @parameters url (str) website's url user_agent (str) specifies the user_agent string num_retries (int) if a download fails due to a problem with the request (4xx) or t...
This function downloads a website's source code. @parameters url (str) website's url user_agent (str) specifies the user_agent string num_retries (int) if a download fails due to a problem with the request (4xx) or the server (5xx) the function calls it self recursively #num_retri...
[ "This", "function", "downloads", "a", "website", "'", "s", "source", "code", ".", "@parameters", "url", "(", "str", ")", "website", "'", "s", "url", "user_agent", "(", "str", ")", "specifies", "the", "user_agent", "string", "num_retries", "(", "int", ")", ...
def download(self, url, user_agent, num_retries): print("Downloading %s ... " % url) headers = {'User-Agent': user_agent} try: resp = requests.get(url, headers=headers, proxies=self.proxy) html_code = resp.text code = resp.status_code if resp.statu...
[ "def", "download", "(", "self", ",", "url", ",", "user_agent", ",", "num_retries", ")", ":", "print", "(", "\"Downloading %s ... \"", "%", "url", ")", "headers", "=", "{", "'User-Agent'", ":", "user_agent", "}", "try", ":", "resp", "=", "requests", ".", ...
This function downloads a website's source code.
[ "This", "function", "downloads", "a", "website", "'", "s", "source", "code", "." ]
[ "\"\"\" This function downloads a website's source code.\r\n @parameters\r\n url (str) website's url\r\n user_agent (str) specifies the user_agent string\r\n num_retries (int) if a download fails due to a problem with the...
[ { "param": "self", "type": null }, { "param": "url", "type": null }, { "param": "user_agent", "type": null }, { "param": "num_retries", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": []...
753e5a9ca5678ba209cb219635eab3de606e0321
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/social_network_analyzer/markets_7days_categorical_analysis.py
[ "MIT" ]
Python
findMostFrequentHashtags
null
def findMostFrequentHashtags(): print("Finding tweets with included hashtags from the Database, over the last 7 days.") print('Querying database and retrieving the data.') # computing the datetime now - 7 days ago sevenDaysAgo = datetime.datetime.utcnow() - datetime.timedelta(days=7) # Mongo Shell...
CATEGORICAL ANALYSIS (BAR-PLOT) PANDAS SECTION
CATEGORICAL ANALYSIS (BAR-PLOT) PANDAS SECTION
[ "CATEGORICAL", "ANALYSIS", "(", "BAR", "-", "PLOT", ")", "PANDAS", "SECTION" ]
def findMostFrequentHashtags(): print("Finding tweets with included hashtags from the Database, over the last 7 days.") print('Querying database and retrieving the data.') sevenDaysAgo = datetime.datetime.utcnow() - datetime.timedelta(days=7) query = {'$and': [{'entities.hashtags.text': {'$exists': 'tru...
[ "def", "findMostFrequentHashtags", "(", ")", ":", "print", "(", "\"Finding tweets with included hashtags from the Database, over the last 7 days.\"", ")", "print", "(", "'Querying database and retrieving the data.'", ")", "sevenDaysAgo", "=", "datetime", ".", "datetime", ".", "...
CATEGORICAL ANALYSIS (BAR-PLOT) PANDAS SECTION
[ "CATEGORICAL", "ANALYSIS", "(", "BAR", "-", "PLOT", ")", "PANDAS", "SECTION" ]
[ "# computing the datetime now - 7 days ago", "# Mongo Shell query", "# db.twitterQuery2.find({'entities.hashtags.text': {$exists : true}}, {'entities.hashtags.text': 1, '_id': 0}).limit(5)", "# creating query + projection for MongoDB", "# running query", "# cursor = cursor.limit(20)", "# Listing counter...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
753e5a9ca5678ba209cb219635eab3de606e0321
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/social_network_analyzer/markets_7days_categorical_analysis.py
[ "MIT" ]
Python
findMostFrequentMentions
null
def findMostFrequentMentions(): print("Finding tweets with included mentions from the Database, over the last 7 days.") print('Querying database and retrieving the data.') # computing the datetime now - 7 days ago sevenDaysAgo = datetime.datetime.utcnow() - datetime.timedelta(days=7) # Mongo Shell...
CATEGORICAL ANALYSIS (BAR-PLOT) PANDAS SECTION
CATEGORICAL ANALYSIS (BAR-PLOT) PANDAS SECTION
[ "CATEGORICAL", "ANALYSIS", "(", "BAR", "-", "PLOT", ")", "PANDAS", "SECTION" ]
def findMostFrequentMentions(): print("Finding tweets with included mentions from the Database, over the last 7 days.") print('Querying database and retrieving the data.') sevenDaysAgo = datetime.datetime.utcnow() - datetime.timedelta(days=7) query = {'$and': [{'entities.user_mentions.screen_name': {'$e...
[ "def", "findMostFrequentMentions", "(", ")", ":", "print", "(", "\"Finding tweets with included mentions from the Database, over the last 7 days.\"", ")", "print", "(", "'Querying database and retrieving the data.'", ")", "sevenDaysAgo", "=", "datetime", ".", "datetime", ".", "...
CATEGORICAL ANALYSIS (BAR-PLOT) PANDAS SECTION
[ "CATEGORICAL", "ANALYSIS", "(", "BAR", "-", "PLOT", ")", "PANDAS", "SECTION" ]
[ "# computing the datetime now - 7 days ago", "# Mongo Shell query", "# db.twitterQuery2.find({'entities.user_mentions.screen_name': {$exists : true}}, {'entities.user_mentions.screen_name': 1, '_id': 0}).limit(5)", "# creating query + projection for MongoDB", "# running query", "# cursor = cursor.limit(20...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
feec8586d12466d83fb6bc70378e3107f5627da7
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/social_network_analyzer/threats_7days_categorical_analysis.py
[ "MIT" ]
Python
findMostFrequentMentions
null
def findMostFrequentMentions(): print("Finding tweets with included mentions from the Database, over the last 7 days.") print('Querying database and retrieving the data.') # computing the datetime now - 7 days ago sevenDaysAgo = datetime.datetime.utcnow() - datetime.timedelta(days=7) # Mongo Shell...
CATEGORICAL ANALYSIS (BAR-PLOT) PANDAS SECTION
CATEGORICAL ANALYSIS (BAR-PLOT) PANDAS SECTION
[ "CATEGORICAL", "ANALYSIS", "(", "BAR", "-", "PLOT", ")", "PANDAS", "SECTION" ]
def findMostFrequentMentions(): print("Finding tweets with included mentions from the Database, over the last 7 days.") print('Querying database and retrieving the data.') sevenDaysAgo = datetime.datetime.utcnow() - datetime.timedelta(days=7) query = {'$and': [{'entities.user_mentions.screen_name': {'$e...
[ "def", "findMostFrequentMentions", "(", ")", ":", "print", "(", "\"Finding tweets with included mentions from the Database, over the last 7 days.\"", ")", "print", "(", "'Querying database and retrieving the data.'", ")", "sevenDaysAgo", "=", "datetime", ".", "datetime", ".", "...
CATEGORICAL ANALYSIS (BAR-PLOT) PANDAS SECTION
[ "CATEGORICAL", "ANALYSIS", "(", "BAR", "-", "PLOT", ")", "PANDAS", "SECTION" ]
[ "# computing the datetime now - 7 days ago", "# Mongo Shell query", "# db.twitterQuery2.find({'entities.user_mentions.screen_name': {$exists : true}}, {'entities.user_mentions.screen_name': 1, '_id': 0}).limit(5)", "# creating query + projection for MongoDB", "# running query", "# cursor = cursor.limit(20...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
a6157ca2c1e88f5e73ba00c3c42e8bbf462aaead
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/descriptive_analysis_summer.py
[ "MIT" ]
Python
time_series_analysis
<not_specific>
def time_series_analysis(self, mongoDateType='mongoDate', entity_type=''): """ Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts) @param ...
Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts) @param db: (Mongo Client) this is the connection returned by Pymongo Clien...
Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts)
[ "Collects", "all", "the", "information", "from", "the", "collection", "and", "presents", "the", "number", "of", "blocked", "IP", "'", "s", "per", "day", "Saves", "the", "results", "in", "csv", "and", "json", "file", "respectively", "for", "later", "process",...
def time_series_analysis(self, mongoDateType='mongoDate', entity_type=''): num_of_docs_in_collection = self.__collection.count() if num_of_docs_in_collection == 0: try: raise Warning("No documents retrieved. Collection {} seems to be empty".format(self.__collection.name)) ...
[ "def", "time_series_analysis", "(", "self", ",", "mongoDateType", "=", "'mongoDate'", ",", "entity_type", "=", "''", ")", ":", "num_of_docs_in_collection", "=", "self", ".", "__collection", ".", "count", "(", ")", "if", "num_of_docs_in_collection", "==", "0", ":...
Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts)
[ "Collects", "all", "the", "information", "from", "the", "collection", "and", "presents", "the", "number", "of", "blocked", "IP", "'", "s", "per", "day", "Saves", "the", "results", "in", "csv", "and", "json", "file", "respectively", "for", "later", "process",...
[ "\"\"\" Collects all the information from the collection and presents the number of blocked IP's per day\r\n Saves the results in csv and json file respectively for later process (stakeholders and Highcharts)\r\n @param\r\n db: (Mongo Client) this is the connection returned...
[ { "param": "self", "type": null }, { "param": "mongoDateType", "type": null }, { "param": "entity_type", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mongoDateType", "type": null, "docstring": null, "docstring_t...
a6157ca2c1e88f5e73ba00c3c42e8bbf462aaead
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/descriptive_analysis_summer.py
[ "MIT" ]
Python
time_series_analysis_per_month
<not_specific>
def time_series_analysis_per_month(self, mongoDateType='mongoDate', entity_type=''): """ Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts) ...
Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts) @param db: (Mongo Client) this is the connection returned by Pymongo Clien...
Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts)
[ "Collects", "all", "the", "information", "from", "the", "collection", "and", "presents", "the", "number", "of", "blocked", "IP", "'", "s", "per", "day", "Saves", "the", "results", "in", "csv", "and", "json", "file", "respectively", "for", "later", "process",...
def time_series_analysis_per_month(self, mongoDateType='mongoDate', entity_type=''): num_of_docs_in_collection = self.__collection.count() if num_of_docs_in_collection == 0: try: raise Warning("No documents retrieved. Collection {} seems to be empty".format(self.__collection....
[ "def", "time_series_analysis_per_month", "(", "self", ",", "mongoDateType", "=", "'mongoDate'", ",", "entity_type", "=", "''", ")", ":", "num_of_docs_in_collection", "=", "self", ".", "__collection", ".", "count", "(", ")", "if", "num_of_docs_in_collection", "==", ...
Collects all the information from the collection and presents the number of blocked IP's per day Saves the results in csv and json file respectively for later process (stakeholders and Highcharts)
[ "Collects", "all", "the", "information", "from", "the", "collection", "and", "presents", "the", "number", "of", "blocked", "IP", "'", "s", "per", "day", "Saves", "the", "results", "in", "csv", "and", "json", "file", "respectively", "for", "later", "process",...
[ "\"\"\" Collects all the information from the collection and presents the number of blocked IP's per day\r\n Saves the results in csv and json file respectively for later process (stakeholders and Highcharts)\r\n @param\r\n db: (Mongo Client) this is the connection returned...
[ { "param": "self", "type": null }, { "param": "mongoDateType", "type": null }, { "param": "entity_type", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mongoDateType", "type": null, "docstring": null, "docstring_t...
a6157ca2c1e88f5e73ba00c3c42e8bbf462aaead
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/descriptive_analysis_summer.py
[ "MIT" ]
Python
data_frame_to_json
null
def data_frame_to_json(self, data_frame, analysis_file_name): """ Given a data_frame creates a list of smaller lists that contain data frame pairs and stores them in a json file @param data_frame filename: (str) the name of the json file to be created ...
Given a data_frame creates a list of smaller lists that contain data frame pairs and stores them in a json file @param data_frame filename: (str) the name of the json file to be created
Given a data_frame creates a list of smaller lists that contain data frame pairs and stores them in a json file @param data_frame filename: (str) the name of the json file to be created
[ "Given", "a", "data_frame", "creates", "a", "list", "of", "smaller", "lists", "that", "contain", "data", "frame", "pairs", "and", "stores", "them", "in", "a", "json", "file", "@param", "data_frame", "filename", ":", "(", "str", ")", "the", "name", "of", ...
def data_frame_to_json(self, data_frame, analysis_file_name): json_analysis_file_name = self.__path + '{}.json'.format(analysis_file_name) data_frame_list = list([]) try: for row in data_frame.itertuples(): highcharts_timestamp = self.__high_charts_timestamp__(row[0])...
[ "def", "data_frame_to_json", "(", "self", ",", "data_frame", ",", "analysis_file_name", ")", ":", "json_analysis_file_name", "=", "self", ".", "__path", "+", "'{}.json'", ".", "format", "(", "analysis_file_name", ")", "data_frame_list", "=", "list", "(", "[", "]...
Given a data_frame creates a list of smaller lists that contain data frame pairs and stores them in a json file @param data_frame filename: (str) the name of the json file to be created
[ "Given", "a", "data_frame", "creates", "a", "list", "of", "smaller", "lists", "that", "contain", "data", "frame", "pairs", "and", "stores", "them", "in", "a", "json", "file", "@param", "data_frame", "filename", ":", "(", "str", ")", "the", "name", "of", ...
[ "\"\"\" Given a data_frame creates a list of smaller lists that contain data frame pairs and stores them in a json file\r\n @param\r\n data_frame\r\n filename: (str) the name of the json file to be created\r\n \"\"\"", "# break down every data frame row in tuple...
[ { "param": "self", "type": null }, { "param": "data_frame", "type": null }, { "param": "analysis_file_name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data_frame", "type": null, "docstring": null, "docstring_toke...
fe63ae7e544a7a7f113b0d561895bab22e1deee7
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/export_collection_data_module.py
[ "MIT" ]
Python
export_to_csv
<not_specific>
def export_to_csv(cursor, dataset_name, csv_header, path): """ This function extracts data from the cursor, then produces a valid csv file with csv_header and saves it to the path. @parameters cursor (cursor) MongoDB's result cursor dataset_name (str) the name o...
This function extracts data from the cursor, then produces a valid csv file with csv_header and saves it to the path. @parameters cursor (cursor) MongoDB's result cursor dataset_name (str) the name of the produced file csv_header (list) list of st...
This function extracts data from the cursor, then produces a valid csv file with csv_header and saves it to the path. @parameters cursor (cursor) MongoDB's result cursor dataset_name (str) the name of the produced file csv_header (list) list of string that correspond to key names for each...
[ "This", "function", "extracts", "data", "from", "the", "cursor", "then", "produces", "a", "valid", "csv", "file", "with", "csv_header", "and", "saves", "it", "to", "the", "path", ".", "@parameters", "cursor", "(", "cursor", ")", "MongoDB", "'", "s", "resul...
def export_to_csv(cursor, dataset_name, csv_header, path): print("\tExporting Collection to csv File...") if cursor.count() == 0: try: raise Warning("No documents retrieved") except Exception as e: print("\nexport_collection_data module > export_to_csv: ", e) ...
[ "def", "export_to_csv", "(", "cursor", ",", "dataset_name", ",", "csv_header", ",", "path", ")", ":", "print", "(", "\"\\tExporting Collection to csv File...\"", ")", "if", "cursor", ".", "count", "(", ")", "==", "0", ":", "try", ":", "raise", "Warning", "("...
This function extracts data from the cursor, then produces a valid csv file with csv_header and saves it to the path.
[ "This", "function", "extracts", "data", "from", "the", "cursor", "then", "produces", "a", "valid", "csv", "file", "with", "csv_header", "and", "saves", "it", "to", "the", "path", "." ]
[ "\"\"\" This function extracts data from the cursor, then produces a valid csv file with csv_header and saves it\r\n to the path.\r\n @parameters\r\n cursor (cursor) MongoDB's result cursor\r\n dataset_name (str) the name of the produced file\r\n csv_header (...
[ { "param": "cursor", "type": null }, { "param": "dataset_name", "type": null }, { "param": "csv_header", "type": null }, { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cursor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dataset_name", "type": null, "docstring": null, "docstring_...
fe63ae7e544a7a7f113b0d561895bab22e1deee7
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/export_collection_data_module.py
[ "MIT" ]
Python
export_to_json
<not_specific>
def export_to_json(cursor, dataset_name, path): """ This function extracts data from the cursor, then produces a valid json file with csv_header and saves it to the path. @parameters cursor (cursor) MongoDB's result cursor dataset_name (str) the name of the prod...
This function extracts data from the cursor, then produces a valid json file with csv_header and saves it to the path. @parameters cursor (cursor) MongoDB's result cursor dataset_name (str) the name of the produced file
This function extracts data from the cursor, then produces a valid json file with csv_header and saves it to the path. @parameters cursor (cursor) MongoDB's result cursor dataset_name (str) the name of the produced file
[ "This", "function", "extracts", "data", "from", "the", "cursor", "then", "produces", "a", "valid", "json", "file", "with", "csv_header", "and", "saves", "it", "to", "the", "path", ".", "@parameters", "cursor", "(", "cursor", ")", "MongoDB", "'", "s", "resu...
def export_to_json(cursor, dataset_name, path): cursor = cursor.rewind() print("\tExporting Collection to json File...") if cursor.count() == 0: try: raise Warning("No documents retrieved") except Exception as e: print("\nexport_collection_data module > export_to_csv:...
[ "def", "export_to_json", "(", "cursor", ",", "dataset_name", ",", "path", ")", ":", "cursor", "=", "cursor", ".", "rewind", "(", ")", "print", "(", "\"\\tExporting Collection to json File...\"", ")", "if", "cursor", ".", "count", "(", ")", "==", "0", ":", ...
This function extracts data from the cursor, then produces a valid json file with csv_header and saves it to the path.
[ "This", "function", "extracts", "data", "from", "the", "cursor", "then", "produces", "a", "valid", "json", "file", "with", "csv_header", "and", "saves", "it", "to", "the", "path", "." ]
[ "\"\"\" This function extracts data from the cursor, then produces a valid json file with csv_header and saves it\r\n to the path.\r\n @parameters\r\n cursor (cursor) MongoDB's result cursor\r\n dataset_name (str) the name of the produced file\r\n \"\"\"", "# ------...
[ { "param": "cursor", "type": null }, { "param": "dataset_name", "type": null }, { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cursor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dataset_name", "type": null, "docstring": null, "docstring_...
fe63ae7e544a7a7f113b0d561895bab22e1deee7
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/export_collection_data_module.py
[ "MIT" ]
Python
zip_directory
null
def zip_directory(dir_path, zip_filename, path): """ This function zips a directory and saves it to the path under the name zip_filename @parameters dir_path (str) the file to zip zip_filename (str) the name of the zipe file path (str) the path to save the...
This function zips a directory and saves it to the path under the name zip_filename @parameters dir_path (str) the file to zip zip_filename (str) the name of the zipe file path (str) the path to save the zip file
This function zips a directory and saves it to the path under the name zip_filename @parameters dir_path (str) the file to zip zip_filename (str) the name of the zipe file path (str) the path to save the zip file
[ "This", "function", "zips", "a", "directory", "and", "saves", "it", "to", "the", "path", "under", "the", "name", "zip_filename", "@parameters", "dir_path", "(", "str", ")", "the", "file", "to", "zip", "zip_filename", "(", "str", ")", "the", "name", "of", ...
def zip_directory(dir_path, zip_filename, path): print("\tZipping Files") with zipfile.ZipFile(path+zip_filename, 'w', zipfile.ZIP_DEFLATED) as zip_file: for root, dirs, files in os.walk(dir_path): for file in files: zip_file.write(os.path.join(root, file), basename(os.path.j...
[ "def", "zip_directory", "(", "dir_path", ",", "zip_filename", ",", "path", ")", ":", "print", "(", "\"\\tZipping Files\"", ")", "with", "zipfile", ".", "ZipFile", "(", "path", "+", "zip_filename", ",", "'w'", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "as", ...
This function zips a directory and saves it to the path under the name zip_filename @parameters dir_path (str) the file to zip zip_filename (str) the name of the zipe file path (str) the path to save the zip file
[ "This", "function", "zips", "a", "directory", "and", "saves", "it", "to", "the", "path", "under", "the", "name", "zip_filename", "@parameters", "dir_path", "(", "str", ")", "the", "file", "to", "zip", "zip_filename", "(", "str", ")", "the", "name", "of", ...
[ "\"\"\" This function zips a directory and saves it to the path under the name zip_filename\r\n @parameters\r\n dir_path (str) the file to zip\r\n zip_filename (str) the name of the zipe file\r\n path (str) the path to save the zip file\r\n \"\"\"", "# -------...
[ { "param": "dir_path", "type": null }, { "param": "zip_filename", "type": null }, { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "dir_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "zip_filename", "type": null, "docstring": null, "docstrin...
fe63ae7e544a7a7f113b0d561895bab22e1deee7
tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring
back-end/utils/export_collection_data_module.py
[ "MIT" ]
Python
datetime_limits_of_month
<not_specific>
def datetime_limits_of_month(utcnow=None, set_year=None, set_month=None): """ This function returns the limits, first and last datetime, of the current month based on the current utc datetime or a user's selection (year, month) @parameters utcnow (datetime or None) ...
This function returns the limits, first and last datetime, of the current month based on the current utc datetime or a user's selection (year, month) @parameters utcnow (datetime or None) the datetime be based on. If None then the user must specify the ...
This function returns the limits, first and last datetime, of the current month based on the current utc datetime or a user's selection (year, month) @parameters utcnow (datetime or None) the datetime be based on. If None then the user must specify the next two parameters set_year (int ...
[ "This", "function", "returns", "the", "limits", "first", "and", "last", "datetime", "of", "the", "current", "month", "based", "on", "the", "current", "utc", "datetime", "or", "a", "user", "'", "s", "selection", "(", "year", "month", ")", "@parameters", "ut...
def datetime_limits_of_month(utcnow=None, set_year=None, set_month=None): if set_year is not None and set_month in range(1, 13): number_of_days_in_month = calendar.monthrange(year=set_year, month=set_month)[1] first_datetime_of_month = datetime(set_year, set_month, 1, 0, 0, 0) last_datetime_...
[ "def", "datetime_limits_of_month", "(", "utcnow", "=", "None", ",", "set_year", "=", "None", ",", "set_month", "=", "None", ")", ":", "if", "set_year", "is", "not", "None", "and", "set_month", "in", "range", "(", "1", ",", "13", ")", ":", "number_of_days...
This function returns the limits, first and last datetime, of the current month based on the current utc datetime or a user's selection (year, month) @parameters utcnow (datetime or None) the datetime be based on.
[ "This", "function", "returns", "the", "limits", "first", "and", "last", "datetime", "of", "the", "current", "month", "based", "on", "the", "current", "utc", "datetime", "or", "a", "user", "'", "s", "selection", "(", "year", "month", ")", "@parameters", "ut...
[ "\"\"\" This function returns the limits, first and last datetime, of the current month based on the current utc\r\n datetime or a user's selection (year, month)\r\n @parameters\r\n utcnow (datetime or None) the datetime be based on. If None then the user must specify the\...
[ { "param": "utcnow", "type": null }, { "param": "set_year", "type": null }, { "param": "set_month", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "utcnow", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "set_year", "type": null, "docstring": null, "docstring_toke...
ef8c9f6da810cb1121455b080554e51514542d9c
rahulz/tweet-analyse-api
tweet_analyse/utils/ai/sentiment.py
[ "Apache-2.0" ]
Python
clean_tweet
<not_specific>
def clean_tweet(text): """ Utility function to clean the text in a tweet by removing links and special characters using regex. """ return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", text).split())
Utility function to clean the text in a tweet by removing links and special characters using regex.
Utility function to clean the text in a tweet by removing links and special characters using regex.
[ "Utility", "function", "to", "clean", "the", "text", "in", "a", "tweet", "by", "removing", "links", "and", "special", "characters", "using", "regex", "." ]
def clean_tweet(text): return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", text).split())
[ "def", "clean_tweet", "(", "text", ")", ":", "return", "' '", ".", "join", "(", "re", ".", "sub", "(", "\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\"", ",", "\" \"", ",", "text", ")", ".", "split", "(", ")", ")" ]
Utility function to clean the text in a tweet by removing links and special characters using regex.
[ "Utility", "function", "to", "clean", "the", "text", "in", "a", "tweet", "by", "removing", "links", "and", "special", "characters", "using", "regex", "." ]
[ "\"\"\"\n Utility function to clean the text in a tweet by removing\n links and special characters using regex.\n \"\"\"" ]
[ { "param": "text", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "text", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5539f6f75ba6581da0416b71e5e41963e33d5944
poxip/django-furl
django_furl/templatetags/furl_tags.py
[ "MIT" ]
Python
furl_update
<not_specific>
def furl_update(url, **kwargs): """ Update url params :param str url - The url to process. :param kwargs - The dictionary of parameters to update the url from (if the specified parameter is present in the url, it is changed). :return The updated url. """ url = furl(url) url.args...
Update url params :param str url - The url to process. :param kwargs - The dictionary of parameters to update the url from (if the specified parameter is present in the url, it is changed). :return The updated url.
Update url params :param str url - The url to process. :param kwargs - The dictionary of parameters to update the url from (if the specified parameter is present in the url, it is changed). :return The updated url.
[ "Update", "url", "params", ":", "param", "str", "url", "-", "The", "url", "to", "process", ".", ":", "param", "kwargs", "-", "The", "dictionary", "of", "parameters", "to", "update", "the", "url", "from", "(", "if", "the", "specified", "parameter", "is", ...
def furl_update(url, **kwargs): url = furl(url) url.args.update(kwargs) return url
[ "def", "furl_update", "(", "url", ",", "**", "kwargs", ")", ":", "url", "=", "furl", "(", "url", ")", "url", ".", "args", ".", "update", "(", "kwargs", ")", "return", "url" ]
Update url params :param str url - The url to process.
[ "Update", "url", "params", ":", "param", "str", "url", "-", "The", "url", "to", "process", "." ]
[ "\"\"\"\n Update url params\n\n :param str url - The url to process.\n :param kwargs - The dictionary of parameters to update the url from\n (if the specified parameter is present in the url, it is changed).\n :return The updated url.\n \"\"\"" ]
[ { "param": "url", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5539f6f75ba6581da0416b71e5e41963e33d5944
poxip/django-furl
django_furl/templatetags/furl_tags.py
[ "MIT" ]
Python
furl_add
<not_specific>
def furl_add(url, **kwargs): """ Add url params to an existing url. Similar to `furl_update`. :param str url - The url to process. :param kwargs - The dictionary of parameters to add to the url (if the specified parameter is present in the url, it is duplicated). :return The updated url. ...
Add url params to an existing url. Similar to `furl_update`. :param str url - The url to process. :param kwargs - The dictionary of parameters to add to the url (if the specified parameter is present in the url, it is duplicated). :return The updated url.
Add url params to an existing url.
[ "Add", "url", "params", "to", "an", "existing", "url", "." ]
def furl_add(url, **kwargs): url = furl(url) return url.add(kwargs)
[ "def", "furl_add", "(", "url", ",", "**", "kwargs", ")", ":", "url", "=", "furl", "(", "url", ")", "return", "url", ".", "add", "(", "kwargs", ")" ]
Add url params to an existing url.
[ "Add", "url", "params", "to", "an", "existing", "url", "." ]
[ "\"\"\"\n Add url params to an existing url. Similar to `furl_update`.\n\n :param str url - The url to process.\n :param kwargs - The dictionary of parameters to add to the url\n (if the specified parameter is present in the url, it is duplicated).\n :return The updated url.\n \"\"\"" ]
[ { "param": "url", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5539f6f75ba6581da0416b71e5e41963e33d5944
poxip/django-furl
django_furl/templatetags/furl_tags.py
[ "MIT" ]
Python
furl_del
<not_specific>
def furl_del(url, *args): """ Remove url params from an existing url. Similar to `furl_update`. :param str url - The url to process. :param args - The list of parameters to remove from the url. :return The updated url. """ url = furl(url) return url.remove(args)
Remove url params from an existing url. Similar to `furl_update`. :param str url - The url to process. :param args - The list of parameters to remove from the url. :return The updated url.
Remove url params from an existing url.
[ "Remove", "url", "params", "from", "an", "existing", "url", "." ]
def furl_del(url, *args): url = furl(url) return url.remove(args)
[ "def", "furl_del", "(", "url", ",", "*", "args", ")", ":", "url", "=", "furl", "(", "url", ")", "return", "url", ".", "remove", "(", "args", ")" ]
Remove url params from an existing url.
[ "Remove", "url", "params", "from", "an", "existing", "url", "." ]
[ "\"\"\"\n Remove url params from an existing url. Similar to `furl_update`.\n\n :param str url - The url to process.\n :param args - The list of parameters to remove from the url.\n :return The updated url.\n \"\"\"" ]
[ { "param": "url", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5539f6f75ba6581da0416b71e5e41963e33d5944
poxip/django-furl
django_furl/templatetags/furl_tags.py
[ "MIT" ]
Python
f_update
<not_specific>
def f_update(url, arg): """ Add url params to an existing url :param str url - The url to process. :param str arg - The key=value string describing the parameter being added. :return The updated url. """ return furl_update(url, **parse_arg(arg))
Add url params to an existing url :param str url - The url to process. :param str arg - The key=value string describing the parameter being added. :return The updated url.
Add url params to an existing url :param str url - The url to process. :param str arg - The key=value string describing the parameter being added. :return The updated url.
[ "Add", "url", "params", "to", "an", "existing", "url", ":", "param", "str", "url", "-", "The", "url", "to", "process", ".", ":", "param", "str", "arg", "-", "The", "key", "=", "value", "string", "describing", "the", "parameter", "being", "added", ".", ...
def f_update(url, arg): return furl_update(url, **parse_arg(arg))
[ "def", "f_update", "(", "url", ",", "arg", ")", ":", "return", "furl_update", "(", "url", ",", "**", "parse_arg", "(", "arg", ")", ")" ]
Add url params to an existing url :param str url - The url to process.
[ "Add", "url", "params", "to", "an", "existing", "url", ":", "param", "str", "url", "-", "The", "url", "to", "process", "." ]
[ "\"\"\"\n Add url params to an existing url\n\n :param str url - The url to process.\n :param str arg - The key=value string describing the parameter being added.\n :return The updated url.\n \"\"\"" ]
[ { "param": "url", "type": null }, { "param": "arg", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "arg", "type": null, "docstring": null, "docstring_tokens": [],...
5539f6f75ba6581da0416b71e5e41963e33d5944
poxip/django-furl
django_furl/templatetags/furl_tags.py
[ "MIT" ]
Python
f_add
<not_specific>
def f_add(url, arg): """ Add url params to an existing url. Similar to `f_update`. :param str url - The url to process. :param str arg - The key=value string describing the parameter being added. If the parameter is present in the url, it's duplicated. :return The updated url. """ r...
Add url params to an existing url. Similar to `f_update`. :param str url - The url to process. :param str arg - The key=value string describing the parameter being added. If the parameter is present in the url, it's duplicated. :return The updated url.
Add url params to an existing url.
[ "Add", "url", "params", "to", "an", "existing", "url", "." ]
def f_add(url, arg): return furl_add(url, **parse_arg(arg))
[ "def", "f_add", "(", "url", ",", "arg", ")", ":", "return", "furl_add", "(", "url", ",", "**", "parse_arg", "(", "arg", ")", ")" ]
Add url params to an existing url.
[ "Add", "url", "params", "to", "an", "existing", "url", "." ]
[ "\"\"\"\n Add url params to an existing url. Similar to `f_update`.\n\n :param str url - The url to process.\n :param str arg - The key=value string describing the parameter being added.\n If the parameter is present in the url, it's duplicated.\n :return The updated url.\n \"\"\"" ]
[ { "param": "url", "type": null }, { "param": "arg", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "arg", "type": null, "docstring": null, "docstring_tokens": [],...
83909c4c6cb84676679078342050f12603b8d128
vtisler/stock_martket_forecast
swagger_server/controllers/delete_controller.py
[ "MIT" ]
Python
delete_delete
<not_specific>
def delete_delete(modelId): # noqa: E501 """Deletes a model from storage # noqa: E501 :param modelId: id of the model to delete :type modelId: str :rtype: None """ return 'do some magic!'
Deletes a model from storage # noqa: E501 :param modelId: id of the model to delete :type modelId: str :rtype: None
Deletes a model from storage noqa: E501
[ "Deletes", "a", "model", "from", "storage", "noqa", ":", "E501" ]
def delete_delete(modelId): """Deletes a model from storage :param modelId: id of the model to delete :type modelId: str :rtype: None """ return 'do some magic!'
[ "def", "delete_delete", "(", "modelId", ")", ":", "return", "'do some magic!'" ]
Deletes a model from storage noqa: E501
[ "Deletes", "a", "model", "from", "storage", "noqa", ":", "E501" ]
[ "# noqa: E501", "\"\"\"Deletes a model from storage\n\n # noqa: E501\n\n :param modelId: id of the model to delete\n :type modelId: str\n\n :rtype: None\n \"\"\"" ]
[ { "param": "modelId", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "None" } ], "raises": [], "params": [ { "identifier": "modelId", "type": null, "docstring": "id of the model to delete", "docstring_tokens": [ "id", "of...
bae17adc3c59ccca75dbbf93dbcedbbcbeee093a
vtisler/stock_martket_forecast
swagger_server/controllers/train_controller.py
[ "MIT" ]
Python
train_post
<not_specific>
def train_post(trainData): # noqa: E501 """Trains a new model # noqa: E501 :param trainData: Neural network training parameters and training data description :type trainData: dict | bytes :rtype: TrainStartedSuccess """ if connexion.request.is_json: trainData = TrainData.from_di...
Trains a new model # noqa: E501 :param trainData: Neural network training parameters and training data description :type trainData: dict | bytes :rtype: TrainStartedSuccess
Trains a new model noqa: E501
[ "Trains", "a", "new", "model", "noqa", ":", "E501" ]
def train_post(trainData): """Trains a new model :param trainData: Neural network training parameters and training data description :type trainData: dict | bytes :rtype: TrainStartedSuccess """ if connexion.request.is_json: trainData = TrainData.from_dict(connexion.request.get_json()) ...
[ "def", "train_post", "(", "trainData", ")", ":", "if", "connexion", ".", "request", ".", "is_json", ":", "trainData", "=", "TrainData", ".", "from_dict", "(", "connexion", ".", "request", ".", "get_json", "(", ")", ")", "return", "'do some magic!'" ]
Trains a new model noqa: E501
[ "Trains", "a", "new", "model", "noqa", ":", "E501" ]
[ "# noqa: E501", "\"\"\"Trains a new model\n\n # noqa: E501\n\n :param trainData: Neural network training parameters and training data description\n :type trainData: dict | bytes\n\n :rtype: TrainStartedSuccess\n \"\"\"", "# noqa: E501" ]
[ { "param": "trainData", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "TrainStartedSuccess" } ], "raises": [], "params": [ { "identifier": "trainData", "type": null, "docstring": "Neural network training parameters and training data description...
f062b1a02e9a5efd81d0b477bba7ca6425061f4f
vtisler/stock_martket_forecast
swagger_server/models/predict_response.py
[ "MIT" ]
Python
indicator
float
def indicator(self) -> float: """Gets the indicator of this PredictResponse. :return: The indicator of this PredictResponse. :rtype: float """ return self._indicator
Gets the indicator of this PredictResponse. :return: The indicator of this PredictResponse. :rtype: float
Gets the indicator of this PredictResponse.
[ "Gets", "the", "indicator", "of", "this", "PredictResponse", "." ]
def indicator(self) -> float: return self._indicator
[ "def", "indicator", "(", "self", ")", "->", "float", ":", "return", "self", ".", "_indicator" ]
Gets the indicator of this PredictResponse.
[ "Gets", "the", "indicator", "of", "this", "PredictResponse", "." ]
[ "\"\"\"Gets the indicator of this PredictResponse.\n\n\n :return: The indicator of this PredictResponse.\n :rtype: float\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": "The indicator of this PredictResponse.", "docstring_tokens": [ "The", "indicator", "of", "this", "PredictResponse", "." ], "type": "float" } ], "raises": [], "params": [ { "identifier": "self...