repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
census-instrumentation/opencensus-python
contrib/opencensus-ext-flask/opencensus/ext/flask/flask_middleware.py
FlaskMiddleware._after_request
def _after_request(self, response): """A function to be run after each request. See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.after_request """ # Do not trace if the url is blacklisted if utils.disable_tracing_url(flask.request.url, self.blacklist_paths): re...
python
def _after_request(self, response): """A function to be run after each request. See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.after_request """ # Do not trace if the url is blacklisted if utils.disable_tracing_url(flask.request.url, self.blacklist_paths): re...
[ "def", "_after_request", "(", "self", ",", "response", ")", ":", "# Do not trace if the url is blacklisted", "if", "utils", ".", "disable_tracing_url", "(", "flask", ".", "request", ".", "url", ",", "self", ".", "blacklist_paths", ")", ":", "return", "response", ...
A function to be run after each request. See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.after_request
[ "A", "function", "to", "be", "run", "after", "each", "request", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-flask/opencensus/ext/flask/flask_middleware.py#L156-L173
train
census-instrumentation/opencensus-python
opencensus/trace/utils.py
get_func_name
def get_func_name(func): """Return a name which includes the module name and function name.""" func_name = getattr(func, '__name__', func.__class__.__name__) module_name = func.__module__ if module_name is not None: module_name = func.__module__ return '{}.{}'.format(module_name, func_n...
python
def get_func_name(func): """Return a name which includes the module name and function name.""" func_name = getattr(func, '__name__', func.__class__.__name__) module_name = func.__module__ if module_name is not None: module_name = func.__module__ return '{}.{}'.format(module_name, func_n...
[ "def", "get_func_name", "(", "func", ")", ":", "func_name", "=", "getattr", "(", "func", ",", "'__name__'", ",", "func", ".", "__class__", ".", "__name__", ")", "module_name", "=", "func", ".", "__module__", "if", "module_name", "is", "not", "None", ":", ...
Return a name which includes the module name and function name.
[ "Return", "a", "name", "which", "includes", "the", "module", "name", "and", "function", "name", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/utils.py#L30-L39
train
census-instrumentation/opencensus-python
opencensus/trace/utils.py
disable_tracing_url
def disable_tracing_url(url, blacklist_paths=None): """Disable tracing on the provided blacklist paths, by default not tracing the health check request. If the url path starts with the blacklisted path, return True. :type blacklist_paths: list :param blacklist_paths: Paths that not tracing. :...
python
def disable_tracing_url(url, blacklist_paths=None): """Disable tracing on the provided blacklist paths, by default not tracing the health check request. If the url path starts with the blacklisted path, return True. :type blacklist_paths: list :param blacklist_paths: Paths that not tracing. :...
[ "def", "disable_tracing_url", "(", "url", ",", "blacklist_paths", "=", "None", ")", ":", "if", "blacklist_paths", "is", "None", ":", "blacklist_paths", "=", "DEFAULT_BLACKLIST_PATHS", "# Remove the 'https?|ftp://' if exists", "url", "=", "re", ".", "sub", "(", "URL_...
Disable tracing on the provided blacklist paths, by default not tracing the health check request. If the url path starts with the blacklisted path, return True. :type blacklist_paths: list :param blacklist_paths: Paths that not tracing. :rtype: bool :returns: True if not tracing, False if tra...
[ "Disable", "tracing", "on", "the", "provided", "blacklist", "paths", "by", "default", "not", "tracing", "the", "health", "check", "request", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/utils.py#L42-L67
train
census-instrumentation/opencensus-python
opencensus/trace/utils.py
disable_tracing_hostname
def disable_tracing_hostname(url, blacklist_hostnames=None): """Disable tracing for the provided blacklist URLs, by default not tracing the exporter url. If the url path starts with the blacklisted path, return True. :type blacklist_hostnames: list :param blacklist_hostnames: URL that not tracing....
python
def disable_tracing_hostname(url, blacklist_hostnames=None): """Disable tracing for the provided blacklist URLs, by default not tracing the exporter url. If the url path starts with the blacklisted path, return True. :type blacklist_hostnames: list :param blacklist_hostnames: URL that not tracing....
[ "def", "disable_tracing_hostname", "(", "url", ",", "blacklist_hostnames", "=", "None", ")", ":", "if", "blacklist_hostnames", "is", "None", ":", "# Exporter host_name are not traced by default", "_tracer", "=", "execution_context", ".", "get_opencensus_tracer", "(", ")",...
Disable tracing for the provided blacklist URLs, by default not tracing the exporter url. If the url path starts with the blacklisted path, return True. :type blacklist_hostnames: list :param blacklist_hostnames: URL that not tracing. :rtype: bool :returns: True if not tracing, False if traci...
[ "Disable", "tracing", "for", "the", "provided", "blacklist", "URLs", "by", "default", "not", "tracing", "the", "exporter", "url", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/utils.py#L70-L95
train
census-instrumentation/opencensus-python
opencensus/trace/trace_options.py
TraceOptions.set_enabled
def set_enabled(self, enabled): """Update the last bit of the trace options byte str. :type enabled: bool :param enabled: Whether enable tracing in this span context or not. """ enabled_bit = '1' if enabled else '0' self.trace_options_byte = str( self.trace_o...
python
def set_enabled(self, enabled): """Update the last bit of the trace options byte str. :type enabled: bool :param enabled: Whether enable tracing in this span context or not. """ enabled_bit = '1' if enabled else '0' self.trace_options_byte = str( self.trace_o...
[ "def", "set_enabled", "(", "self", ",", "enabled", ")", ":", "enabled_bit", "=", "'1'", "if", "enabled", "else", "'0'", "self", ".", "trace_options_byte", "=", "str", "(", "self", ".", "trace_options_byte", ")", "[", ":", "-", "1", "]", "+", "enabled_bit...
Update the last bit of the trace options byte str. :type enabled: bool :param enabled: Whether enable tracing in this span context or not.
[ "Update", "the", "last", "bit", "of", "the", "trace", "options", "byte", "str", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/trace_options.py#L70-L79
train
census-instrumentation/opencensus-python
opencensus/common/monitored_resource/k8s_utils.py
get_k8s_metadata
def get_k8s_metadata(): """Get kubernetes container metadata, as on GCP GKE.""" k8s_metadata = {} gcp_cluster = (gcp_metadata_config.GcpMetadataConfig .get_attribute(gcp_metadata_config.CLUSTER_NAME_KEY)) if gcp_cluster is not None: k8s_metadata[CLUSTER_NAME_KEY] = gcp_cluste...
python
def get_k8s_metadata(): """Get kubernetes container metadata, as on GCP GKE.""" k8s_metadata = {} gcp_cluster = (gcp_metadata_config.GcpMetadataConfig .get_attribute(gcp_metadata_config.CLUSTER_NAME_KEY)) if gcp_cluster is not None: k8s_metadata[CLUSTER_NAME_KEY] = gcp_cluste...
[ "def", "get_k8s_metadata", "(", ")", ":", "k8s_metadata", "=", "{", "}", "gcp_cluster", "=", "(", "gcp_metadata_config", ".", "GcpMetadataConfig", ".", "get_attribute", "(", "gcp_metadata_config", ".", "CLUSTER_NAME_KEY", ")", ")", "if", "gcp_cluster", "is", "not"...
Get kubernetes container metadata, as on GCP GKE.
[ "Get", "kubernetes", "container", "metadata", "as", "on", "GCP", "GKE", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/monitored_resource/k8s_utils.py#L50-L64
train
census-instrumentation/opencensus-python
opencensus/tags/tag_map.py
TagMap.insert
def insert(self, key, value): """Inserts a key and value in the map if the map does not already contain the key. :type key: :class: '~opencensus.tags.tag_key.TagKey' :param key: a tag key to insert into the map :type value: :class: '~opencensus.tags.tag_value.TagValue' ...
python
def insert(self, key, value): """Inserts a key and value in the map if the map does not already contain the key. :type key: :class: '~opencensus.tags.tag_key.TagKey' :param key: a tag key to insert into the map :type value: :class: '~opencensus.tags.tag_value.TagValue' ...
[ "def", "insert", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "in", "self", ".", "map", ":", "return", "try", ":", "tag_key", "=", "TagKey", "(", "key", ")", "tag_val", "=", "TagValue", "(", "value", ")", "self", ".", "map", "[",...
Inserts a key and value in the map if the map does not already contain the key. :type key: :class: '~opencensus.tags.tag_key.TagKey' :param key: a tag key to insert into the map :type value: :class: '~opencensus.tags.tag_value.TagValue' :param value: a tag value that is associa...
[ "Inserts", "a", "key", "and", "value", "in", "the", "map", "if", "the", "map", "does", "not", "already", "contain", "the", "key", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/tags/tag_map.py#L35-L55
train
census-instrumentation/opencensus-python
opencensus/tags/tag_map.py
TagMap.update
def update(self, key, value): """Updates the map by updating the value of a key :type key: :class: '~opencensus.tags.tag_key.TagKey' :param key: A tag key to be updated :type value: :class: '~opencensus.tags.tag_value.TagValue' :param value: The value to update the key to in th...
python
def update(self, key, value): """Updates the map by updating the value of a key :type key: :class: '~opencensus.tags.tag_key.TagKey' :param key: A tag key to be updated :type value: :class: '~opencensus.tags.tag_value.TagValue' :param value: The value to update the key to in th...
[ "def", "update", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "in", "self", ".", "map", ":", "self", ".", "map", "[", "key", "]", "=", "value" ]
Updates the map by updating the value of a key :type key: :class: '~opencensus.tags.tag_key.TagKey' :param key: A tag key to be updated :type value: :class: '~opencensus.tags.tag_value.TagValue' :param value: The value to update the key to in the map
[ "Updates", "the", "map", "by", "updating", "the", "value", "of", "a", "key" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/tags/tag_map.py#L68-L79
train
census-instrumentation/opencensus-python
contrib/opencensus-ext-threading/opencensus/ext/threading/trace.py
trace_integration
def trace_integration(tracer=None): """Wrap threading functions to trace.""" log.info("Integrated module: {}".format(MODULE_NAME)) # Wrap the threading start function start_func = getattr(threading.Thread, "start") setattr( threading.Thread, start_func.__name__, wrap_threading_start(start_fu...
python
def trace_integration(tracer=None): """Wrap threading functions to trace.""" log.info("Integrated module: {}".format(MODULE_NAME)) # Wrap the threading start function start_func = getattr(threading.Thread, "start") setattr( threading.Thread, start_func.__name__, wrap_threading_start(start_fu...
[ "def", "trace_integration", "(", "tracer", "=", "None", ")", ":", "log", ".", "info", "(", "\"Integrated module: {}\"", ".", "format", "(", "MODULE_NAME", ")", ")", "# Wrap the threading start function", "start_func", "=", "getattr", "(", "threading", ".", "Thread...
Wrap threading functions to trace.
[ "Wrap", "threading", "functions", "to", "trace", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-threading/opencensus/ext/threading/trace.py#L29-L56
train
census-instrumentation/opencensus-python
contrib/opencensus-ext-threading/opencensus/ext/threading/trace.py
wrap_threading_start
def wrap_threading_start(start_func): """Wrap the start function from thread. Put the tracer informations in the threading object. """ def call(self): self._opencensus_context = ( execution_context.get_opencensus_full_context() ) return start_func(self) return c...
python
def wrap_threading_start(start_func): """Wrap the start function from thread. Put the tracer informations in the threading object. """ def call(self): self._opencensus_context = ( execution_context.get_opencensus_full_context() ) return start_func(self) return c...
[ "def", "wrap_threading_start", "(", "start_func", ")", ":", "def", "call", "(", "self", ")", ":", "self", ".", "_opencensus_context", "=", "(", "execution_context", ".", "get_opencensus_full_context", "(", ")", ")", "return", "start_func", "(", "self", ")", "r...
Wrap the start function from thread. Put the tracer informations in the threading object.
[ "Wrap", "the", "start", "function", "from", "thread", ".", "Put", "the", "tracer", "informations", "in", "the", "threading", "object", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-threading/opencensus/ext/threading/trace.py#L59-L70
train
census-instrumentation/opencensus-python
contrib/opencensus-ext-threading/opencensus/ext/threading/trace.py
wrap_threading_run
def wrap_threading_run(run_func): """Wrap the run function from thread. Get the tracer informations from the threading object and set it as current tracer. """ def call(self): execution_context.set_opencensus_full_context( *self._opencensus_context ) return run_func(...
python
def wrap_threading_run(run_func): """Wrap the run function from thread. Get the tracer informations from the threading object and set it as current tracer. """ def call(self): execution_context.set_opencensus_full_context( *self._opencensus_context ) return run_func(...
[ "def", "wrap_threading_run", "(", "run_func", ")", ":", "def", "call", "(", "self", ")", ":", "execution_context", ".", "set_opencensus_full_context", "(", "*", "self", ".", "_opencensus_context", ")", "return", "run_func", "(", "self", ")", "return", "call" ]
Wrap the run function from thread. Get the tracer informations from the threading object and set it as current tracer.
[ "Wrap", "the", "run", "function", "from", "thread", ".", "Get", "the", "tracer", "informations", "from", "the", "threading", "object", "and", "set", "it", "as", "current", "tracer", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-threading/opencensus/ext/threading/trace.py#L73-L84
train
census-instrumentation/opencensus-python
opencensus/trace/attributes.py
Attributes.format_attributes_json
def format_attributes_json(self): """Convert the Attributes object to json format.""" attributes_json = {} for key, value in self.attributes.items(): key = utils.check_str_length(key)[0] value = _format_attribute_value(value) if value is not None: ...
python
def format_attributes_json(self): """Convert the Attributes object to json format.""" attributes_json = {} for key, value in self.attributes.items(): key = utils.check_str_length(key)[0] value = _format_attribute_value(value) if value is not None: ...
[ "def", "format_attributes_json", "(", "self", ")", ":", "attributes_json", "=", "{", "}", "for", "key", ",", "value", "in", "self", ".", "attributes", ".", "items", "(", ")", ":", "key", "=", "utils", ".", "check_str_length", "(", "key", ")", "[", "0",...
Convert the Attributes object to json format.
[ "Convert", "the", "Attributes", "object", "to", "json", "format", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/attributes.py#L59-L74
train
census-instrumentation/opencensus-python
opencensus/stats/aggregation_data.py
DistributionAggregationData.add_sample
def add_sample(self, value, timestamp, attachments): """Adding a sample to Distribution Aggregation Data""" self._count_data += 1 bucket = self.increment_bucket_count(value) if attachments is not None and self.exemplars is not None: self.exemplars[bucket] = Exemplar(value, t...
python
def add_sample(self, value, timestamp, attachments): """Adding a sample to Distribution Aggregation Data""" self._count_data += 1 bucket = self.increment_bucket_count(value) if attachments is not None and self.exemplars is not None: self.exemplars[bucket] = Exemplar(value, t...
[ "def", "add_sample", "(", "self", ",", "value", ",", "timestamp", ",", "attachments", ")", ":", "self", ".", "_count_data", "+=", "1", "bucket", "=", "self", ".", "increment_bucket_count", "(", "value", ")", "if", "attachments", "is", "not", "None", "and",...
Adding a sample to Distribution Aggregation Data
[ "Adding", "a", "sample", "to", "Distribution", "Aggregation", "Data" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/aggregation_data.py#L250-L265
train
census-instrumentation/opencensus-python
opencensus/stats/aggregation_data.py
DistributionAggregationData.increment_bucket_count
def increment_bucket_count(self, value): """Increment the bucket count based on a given value from the user""" if len(self._bounds) == 0: self._counts_per_bucket[0] += 1 return 0 for ii, bb in enumerate(self._bounds): if value < bb: self._coun...
python
def increment_bucket_count(self, value): """Increment the bucket count based on a given value from the user""" if len(self._bounds) == 0: self._counts_per_bucket[0] += 1 return 0 for ii, bb in enumerate(self._bounds): if value < bb: self._coun...
[ "def", "increment_bucket_count", "(", "self", ",", "value", ")", ":", "if", "len", "(", "self", ".", "_bounds", ")", "==", "0", ":", "self", ".", "_counts_per_bucket", "[", "0", "]", "+=", "1", "return", "0", "for", "ii", ",", "bb", "in", "enumerate"...
Increment the bucket count based on a given value from the user
[ "Increment", "the", "bucket", "count", "based", "on", "a", "given", "value", "from", "the", "user" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/aggregation_data.py#L267-L280
train
fhamborg/news-please
newsplease/single_crawler.py
SingleCrawler.load_crawler
def load_crawler(self, crawler, url, ignore_regex): """ Loads the given crawler with the given url. :param class crawler: class of the crawler to load :param str url: url to start the crawler with :param regex ignore_regex: to be able to ignore urls that match this ...
python
def load_crawler(self, crawler, url, ignore_regex): """ Loads the given crawler with the given url. :param class crawler: class of the crawler to load :param str url: url to start the crawler with :param regex ignore_regex: to be able to ignore urls that match this ...
[ "def", "load_crawler", "(", "self", ",", "crawler", ",", "url", ",", "ignore_regex", ")", ":", "self", ".", "process", "=", "CrawlerProcess", "(", "self", ".", "cfg", ".", "get_scrapy_options", "(", ")", ")", "self", ".", "process", ".", "crawl", "(", ...
Loads the given crawler with the given url. :param class crawler: class of the crawler to load :param str url: url to start the crawler with :param regex ignore_regex: to be able to ignore urls that match this regex code
[ "Loads", "the", "given", "crawler", "with", "the", "given", "url", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/single_crawler.py#L224-L239
train
fhamborg/news-please
newsplease/pipeline/extractor/extractors/lang_detect_extractor.py
LangExtractor._language
def _language(self, item): """Returns the language of the extracted article by analyzing metatags and inspecting the visible text with langdetect""" response = item['spider_response'].body root = html.fromstring(response) # Check for lang-attributes lang = root.get('lan...
python
def _language(self, item): """Returns the language of the extracted article by analyzing metatags and inspecting the visible text with langdetect""" response = item['spider_response'].body root = html.fromstring(response) # Check for lang-attributes lang = root.get('lan...
[ "def", "_language", "(", "self", ",", "item", ")", ":", "response", "=", "item", "[", "'spider_response'", "]", ".", "body", "root", "=", "html", ".", "fromstring", "(", "response", ")", "# Check for lang-attributes", "lang", "=", "root", ".", "get", "(", ...
Returns the language of the extracted article by analyzing metatags and inspecting the visible text with langdetect
[ "Returns", "the", "language", "of", "the", "extracted", "article", "by", "analyzing", "metatags", "and", "inspecting", "the", "visible", "text", "with", "langdetect" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/extractors/lang_detect_extractor.py#L21-L74
train
fhamborg/news-please
newsplease/crawler/spiders/download_crawler.py
Download.parse
def parse(self, response): """ Passes the response to the pipeline. :param obj response: The scrapy response """ if not self.helper.parse_crawler.content_type(response): return yield self.helper.parse_crawler.pass_to_pipeline( response, ...
python
def parse(self, response): """ Passes the response to the pipeline. :param obj response: The scrapy response """ if not self.helper.parse_crawler.content_type(response): return yield self.helper.parse_crawler.pass_to_pipeline( response, ...
[ "def", "parse", "(", "self", ",", "response", ")", ":", "if", "not", "self", ".", "helper", ".", "parse_crawler", ".", "content_type", "(", "response", ")", ":", "return", "yield", "self", ".", "helper", ".", "parse_crawler", ".", "pass_to_pipeline", "(", ...
Passes the response to the pipeline. :param obj response: The scrapy response
[ "Passes", "the", "response", "to", "the", "pipeline", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/crawler/spiders/download_crawler.py#L28-L40
train
fhamborg/news-please
newsplease/pipeline/extractor/comparer/comparer_Language.py
ComparerLanguage.extract
def extract(self, item, list_article_candidate): """Compares how often any language was detected. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the language which wa...
python
def extract(self, item, list_article_candidate): """Compares how often any language was detected. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the language which wa...
[ "def", "extract", "(", "self", ",", "item", ",", "list_article_candidate", ")", ":", "# Save extracted languages in list", "languages_extracted", "=", "[", "]", "# Save the extracted language of newspaper in extra variable, because newspaper extract meta-language", "# which is very a...
Compares how often any language was detected. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the language which was most frequently detected
[ "Compares", "how", "often", "any", "language", "was", "detected", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_Language.py#L4-L49
train
fhamborg/news-please
newsplease/pipeline/extractor/comparer/comparer_date.py
ComparerDate.extract
def extract(self, item, list_article_candidate): """Compares the extracted publish dates. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely publish date ...
python
def extract(self, item, list_article_candidate): """Compares the extracted publish dates. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely publish date ...
[ "def", "extract", "(", "self", ",", "item", ",", "list_article_candidate", ")", ":", "list_publish_date", "=", "[", "]", "for", "article_candidate", "in", "list_article_candidate", ":", "if", "article_candidate", ".", "publish_date", "!=", "None", ":", "list_publi...
Compares the extracted publish dates. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely publish date
[ "Compares", "the", "extracted", "publish", "dates", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_date.py#L4-L28
train
fhamborg/news-please
newsplease/helper_classes/heuristics.py
Heuristics.meta_contains_article_keyword
def meta_contains_article_keyword(self, response, site_dict): """ Determines wether the response's meta data contains the keyword 'article' :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :return bool: Determines wether...
python
def meta_contains_article_keyword(self, response, site_dict): """ Determines wether the response's meta data contains the keyword 'article' :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :return bool: Determines wether...
[ "def", "meta_contains_article_keyword", "(", "self", ",", "response", ",", "site_dict", ")", ":", "contains_meta", "=", "response", ".", "xpath", "(", "'//meta'", ")", ".", "re", "(", "'(= ?[\"\\'][^\"\\']*article[^\"\\']*[\"\\'])'", ")", "if", "not", "contains_meta...
Determines wether the response's meta data contains the keyword 'article' :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :return bool: Determines wether the reponse's meta data contains the keyword 'article'
[ "Determines", "wether", "the", "response", "s", "meta", "data", "contains", "the", "keyword", "article" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/heuristics.py#L36-L52
train
fhamborg/news-please
newsplease/helper_classes/heuristics.py
Heuristics.linked_headlines
def linked_headlines(self, response, site_dict, check_self=False): """ Checks how many of the headlines on the site contain links. :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :param bool check_self: Check headlines/ ...
python
def linked_headlines(self, response, site_dict, check_self=False): """ Checks how many of the headlines on the site contain links. :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :param bool check_self: Check headlines/ ...
[ "def", "linked_headlines", "(", "self", ",", "response", ",", "site_dict", ",", "check_self", "=", "False", ")", ":", "h_all", "=", "0", "h_linked", "=", "0", "domain", "=", "UrlExtractor", ".", "get_allowed_domain", "(", "site_dict", "[", "\"url\"", "]", ...
Checks how many of the headlines on the site contain links. :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :param bool check_self: Check headlines/ headlines_containing_link_to_same_domain ...
[ "Checks", "how", "many", "of", "the", "headlines", "on", "the", "site", "contain", "links", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/heuristics.py#L73-L109
train
fhamborg/news-please
newsplease/helper_classes/heuristics.py
Heuristics.is_not_from_subdomain
def is_not_from_subdomain(self, response, site_dict): """ Ensures the response's url isn't from a subdomain. :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :return bool: Determines if the response's url is from a subdomain ...
python
def is_not_from_subdomain(self, response, site_dict): """ Ensures the response's url isn't from a subdomain. :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :return bool: Determines if the response's url is from a subdomain ...
[ "def", "is_not_from_subdomain", "(", "self", ",", "response", ",", "site_dict", ")", ":", "root_url", "=", "re", ".", "sub", "(", "re_url_root", ",", "''", ",", "site_dict", "[", "\"url\"", "]", ")", "return", "UrlExtractor", ".", "get_allowed_domain", "(", ...
Ensures the response's url isn't from a subdomain. :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :return bool: Determines if the response's url is from a subdomain
[ "Ensures", "the", "response", "s", "url", "isn", "t", "from", "a", "subdomain", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/heuristics.py#L122-L133
train
fhamborg/news-please
newsplease/pipeline/extractor/comparer/comparer_description.py
ComparerDescription.extract
def extract(self, item, list_article_candidate): """Compares the extracted descriptions. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely description ...
python
def extract(self, item, list_article_candidate): """Compares the extracted descriptions. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely description ...
[ "def", "extract", "(", "self", ",", "item", ",", "list_article_candidate", ")", ":", "list_description", "=", "[", "]", "\"\"\" The descriptions of the article candidates and the respective extractors are saved\n in a tuple in list_description.\n \"\"\"", "for", "articl...
Compares the extracted descriptions. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely description
[ "Compares", "the", "extracted", "descriptions", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_description.py#L6-L33
train
fhamborg/news-please
newsplease/pipeline/pipelines.py
PandasStorage.close_spider
def close_spider(self, _spider): """ Write out to file """ self.df['date_download'] = pd.to_datetime( self.df['date_download'], errors='coerce', infer_datetime_format=True ) self.df['date_modify'] = pd.to_datetime( self.df['date_modify'], errors='c...
python
def close_spider(self, _spider): """ Write out to file """ self.df['date_download'] = pd.to_datetime( self.df['date_download'], errors='coerce', infer_datetime_format=True ) self.df['date_modify'] = pd.to_datetime( self.df['date_modify'], errors='c...
[ "def", "close_spider", "(", "self", ",", "_spider", ")", ":", "self", ".", "df", "[", "'date_download'", "]", "=", "pd", ".", "to_datetime", "(", "self", ".", "df", "[", "'date_download'", "]", ",", "errors", "=", "'coerce'", ",", "infer_datetime_format", ...
Write out to file
[ "Write", "out", "to", "file" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/pipelines.py#L643-L657
train
fhamborg/news-please
newsplease/pipeline/extractor/extractors/date_extractor.py
DateExtractor._publish_date
def _publish_date(self, item): """Returns the publish_date of the extracted article.""" url = item['url'] html = deepcopy(item['spider_response'].body) publish_date = None try: if html is None: request = urllib2.Request(url) # Using a...
python
def _publish_date(self, item): """Returns the publish_date of the extracted article.""" url = item['url'] html = deepcopy(item['spider_response'].body) publish_date = None try: if html is None: request = urllib2.Request(url) # Using a...
[ "def", "_publish_date", "(", "self", ",", "item", ")", ":", "url", "=", "item", "[", "'url'", "]", "html", "=", "deepcopy", "(", "item", "[", "'spider_response'", "]", ".", "body", ")", "publish_date", "=", "None", "try", ":", "if", "html", "is", "No...
Returns the publish_date of the extracted article.
[ "Returns", "the", "publish_date", "of", "the", "extracted", "article", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/extractors/date_extractor.py#L30-L58
train
fhamborg/news-please
newsplease/pipeline/extractor/extractors/date_extractor.py
DateExtractor._extract_from_url
def _extract_from_url(self, url): """Try to extract from the article URL - simple but might work as a fallback""" # Regex by Newspaper3k - https://github.com/codelucas/newspaper/blob/master/newspaper/urls.py m = re.search(re_pub_date, url) if m: return self.parse_date_str(m...
python
def _extract_from_url(self, url): """Try to extract from the article URL - simple but might work as a fallback""" # Regex by Newspaper3k - https://github.com/codelucas/newspaper/blob/master/newspaper/urls.py m = re.search(re_pub_date, url) if m: return self.parse_date_str(m...
[ "def", "_extract_from_url", "(", "self", ",", "url", ")", ":", "# Regex by Newspaper3k - https://github.com/codelucas/newspaper/blob/master/newspaper/urls.py", "m", "=", "re", ".", "search", "(", "re_pub_date", ",", "url", ")", "if", "m", ":", "return", "self", ".", ...
Try to extract from the article URL - simple but might work as a fallback
[ "Try", "to", "extract", "from", "the", "article", "URL", "-", "simple", "but", "might", "work", "as", "a", "fallback" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/extractors/date_extractor.py#L67-L74
train
fhamborg/news-please
newsplease/pipeline/extractor/cleaner.py
Cleaner.delete_tags
def delete_tags(self, arg): """Removes html-tags from extracted data. :param arg: A string, the string which shall be cleaned :return: A string, the cleaned string """ if len(arg) > 0: raw = html.fromstring(arg) return raw.text_content().strip() ...
python
def delete_tags(self, arg): """Removes html-tags from extracted data. :param arg: A string, the string which shall be cleaned :return: A string, the cleaned string """ if len(arg) > 0: raw = html.fromstring(arg) return raw.text_content().strip() ...
[ "def", "delete_tags", "(", "self", ",", "arg", ")", ":", "if", "len", "(", "arg", ")", ">", "0", ":", "raw", "=", "html", ".", "fromstring", "(", "arg", ")", "return", "raw", ".", "text_content", "(", ")", ".", "strip", "(", ")", "return", "arg" ...
Removes html-tags from extracted data. :param arg: A string, the string which shall be cleaned :return: A string, the cleaned string
[ "Removes", "html", "-", "tags", "from", "extracted", "data", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/cleaner.py#L22-L33
train
fhamborg/news-please
newsplease/pipeline/extractor/cleaner.py
Cleaner.delete_whitespaces
def delete_whitespaces(self, arg): """Removes newlines, tabs and whitespaces at the beginning, the end and if there is more than one. :param arg: A string, the string which shell be cleaned :return: A string, the cleaned string """ # Deletes whitespaces after a newline a...
python
def delete_whitespaces(self, arg): """Removes newlines, tabs and whitespaces at the beginning, the end and if there is more than one. :param arg: A string, the string which shell be cleaned :return: A string, the cleaned string """ # Deletes whitespaces after a newline a...
[ "def", "delete_whitespaces", "(", "self", ",", "arg", ")", ":", "# Deletes whitespaces after a newline", "arg", "=", "re", ".", "sub", "(", "re_newline_spc", ",", "''", ",", "arg", ")", "# Deletes every whitespace, tabulator, newline at the beginning of the string", "arg"...
Removes newlines, tabs and whitespaces at the beginning, the end and if there is more than one. :param arg: A string, the string which shell be cleaned :return: A string, the cleaned string
[ "Removes", "newlines", "tabs", "and", "whitespaces", "at", "the", "beginning", "the", "end", "and", "if", "there", "is", "more", "than", "one", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/cleaner.py#L35-L51
train
fhamborg/news-please
newsplease/pipeline/extractor/cleaner.py
Cleaner.do_cleaning
def do_cleaning(self, arg): """Does the actual cleaning by using the delete methods above. :param arg: A string, the string which shell be cleaned. Or a list, in which case each of the strings within the list is cleaned. :return: A string, the cleaned string. Or a list with cleaned stri...
python
def do_cleaning(self, arg): """Does the actual cleaning by using the delete methods above. :param arg: A string, the string which shell be cleaned. Or a list, in which case each of the strings within the list is cleaned. :return: A string, the cleaned string. Or a list with cleaned stri...
[ "def", "do_cleaning", "(", "self", ",", "arg", ")", ":", "if", "arg", "is", "not", "None", ":", "if", "isinstance", "(", "arg", ",", "list", ")", ":", "newlist", "=", "[", "]", "for", "entry", "in", "arg", ":", "newlist", ".", "append", "(", "sel...
Does the actual cleaning by using the delete methods above. :param arg: A string, the string which shell be cleaned. Or a list, in which case each of the strings within the list is cleaned. :return: A string, the cleaned string. Or a list with cleaned string entries.
[ "Does", "the", "actual", "cleaning", "by", "using", "the", "delete", "methods", "above", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/cleaner.py#L53-L75
train
fhamborg/news-please
newsplease/pipeline/extractor/cleaner.py
Cleaner.clean
def clean(self, list_article_candidates): """Iterates over each article_candidate and cleans every extracted data. :param list_article_candidates: A list, the list of ArticleCandidate-Objects which have been extracted :return: A list, the list with the cleaned ArticleCandidate-Objects "...
python
def clean(self, list_article_candidates): """Iterates over each article_candidate and cleans every extracted data. :param list_article_candidates: A list, the list of ArticleCandidate-Objects which have been extracted :return: A list, the list with the cleaned ArticleCandidate-Objects "...
[ "def", "clean", "(", "self", ",", "list_article_candidates", ")", ":", "# Save cleaned article_candidates in results.", "results", "=", "[", "]", "for", "article_candidate", "in", "list_article_candidates", ":", "article_candidate", ".", "title", "=", "self", ".", "do...
Iterates over each article_candidate and cleans every extracted data. :param list_article_candidates: A list, the list of ArticleCandidate-Objects which have been extracted :return: A list, the list with the cleaned ArticleCandidate-Objects
[ "Iterates", "over", "each", "article_candidate", "and", "cleans", "every", "extracted", "data", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/cleaner.py#L77-L96
train
fhamborg/news-please
newsplease/pipeline/extractor/comparer/comparer.py
Comparer.compare
def compare(self, item, article_candidates): """Compares the article candidates using the different submodules and saves the best results in new ArticleCandidate object :param item: The NewscrawlerItem related to the ArticleCandidates :param article_candidates: The list of ArticleCandid...
python
def compare(self, item, article_candidates): """Compares the article candidates using the different submodules and saves the best results in new ArticleCandidate object :param item: The NewscrawlerItem related to the ArticleCandidates :param article_candidates: The list of ArticleCandid...
[ "def", "compare", "(", "self", ",", "item", ",", "article_candidates", ")", ":", "result", "=", "ArticleCandidate", "(", ")", "result", ".", "title", "=", "self", ".", "comparer_title", ".", "extract", "(", "item", ",", "article_candidates", ")", "result", ...
Compares the article candidates using the different submodules and saves the best results in new ArticleCandidate object :param item: The NewscrawlerItem related to the ArticleCandidates :param article_candidates: The list of ArticleCandidate-Objects which have been extracted :return: A...
[ "Compares", "the", "article", "candidates", "using", "the", "different", "submodules", "and", "saves", "the", "best", "results", "in", "new", "ArticleCandidate", "object" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer.py#L24-L42
train
fhamborg/news-please
newsplease/crawler/spiders/rss_crawler.py
RssCrawler.parse
def parse(self, response): """ Extracts the Rss Feed and initiates crawling it. :param obj response: The scrapy response """ yield scrapy.Request(self.helper.url_extractor.get_rss_url(response), callback=self.rss_parse)
python
def parse(self, response): """ Extracts the Rss Feed and initiates crawling it. :param obj response: The scrapy response """ yield scrapy.Request(self.helper.url_extractor.get_rss_url(response), callback=self.rss_parse)
[ "def", "parse", "(", "self", ",", "response", ")", ":", "yield", "scrapy", ".", "Request", "(", "self", ".", "helper", ".", "url_extractor", ".", "get_rss_url", "(", "response", ")", ",", "callback", "=", "self", ".", "rss_parse", ")" ]
Extracts the Rss Feed and initiates crawling it. :param obj response: The scrapy response
[ "Extracts", "the", "Rss", "Feed", "and", "initiates", "crawling", "it", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/crawler/spiders/rss_crawler.py#L42-L49
train
fhamborg/news-please
newsplease/crawler/spiders/rss_crawler.py
RssCrawler.supports_site
def supports_site(url): """ Rss Crawler are supported if by every site containing an rss feed. Determines if this crawler works on the given url. :param str url: The url to test :return bool: Determines wether this crawler work on the given url """ # Follow red...
python
def supports_site(url): """ Rss Crawler are supported if by every site containing an rss feed. Determines if this crawler works on the given url. :param str url: The url to test :return bool: Determines wether this crawler work on the given url """ # Follow red...
[ "def", "supports_site", "(", "url", ")", ":", "# Follow redirects", "opener", "=", "urllib2", ".", "build_opener", "(", "urllib2", ".", "HTTPRedirectHandler", ")", "redirect", "=", "opener", ".", "open", "(", "url", ")", ".", "url", "response", "=", "urllib2...
Rss Crawler are supported if by every site containing an rss feed. Determines if this crawler works on the given url. :param str url: The url to test :return bool: Determines wether this crawler work on the given url
[ "Rss", "Crawler", "are", "supported", "if", "by", "every", "site", "containing", "an", "rss", "feed", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/crawler/spiders/rss_crawler.py#L86-L102
train
fhamborg/news-please
newsplease/helper_classes/url_extractor.py
UrlExtractor.get_allowed_domain
def get_allowed_domain(url, allow_subdomains=True): """ Determines the url's domain. :param str url: the url to extract the allowed domain from :param bool allow_subdomains: determines wether to include subdomains :return str: subdomains.domain.topleveldomain or domain.topleveld...
python
def get_allowed_domain(url, allow_subdomains=True): """ Determines the url's domain. :param str url: the url to extract the allowed domain from :param bool allow_subdomains: determines wether to include subdomains :return str: subdomains.domain.topleveldomain or domain.topleveld...
[ "def", "get_allowed_domain", "(", "url", ",", "allow_subdomains", "=", "True", ")", ":", "if", "allow_subdomains", ":", "return", "re", ".", "sub", "(", "re_www", ",", "''", ",", "re", ".", "search", "(", "r'[^/]+\\.[^/]+'", ",", "url", ")", ".", "group"...
Determines the url's domain. :param str url: the url to extract the allowed domain from :param bool allow_subdomains: determines wether to include subdomains :return str: subdomains.domain.topleveldomain or domain.topleveldomain
[ "Determines", "the", "url", "s", "domain", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L31-L42
train
fhamborg/news-please
newsplease/helper_classes/url_extractor.py
UrlExtractor.get_subdomain
def get_subdomain(url): """ Determines the domain's subdomains. :param str url: the url to extract any subdomains from :return str: subdomains of url """ allowed_domain = UrlExtractor.get_allowed_domain(url) return allowed_domain[:len(allowed_domain) - len( ...
python
def get_subdomain(url): """ Determines the domain's subdomains. :param str url: the url to extract any subdomains from :return str: subdomains of url """ allowed_domain = UrlExtractor.get_allowed_domain(url) return allowed_domain[:len(allowed_domain) - len( ...
[ "def", "get_subdomain", "(", "url", ")", ":", "allowed_domain", "=", "UrlExtractor", ".", "get_allowed_domain", "(", "url", ")", "return", "allowed_domain", "[", ":", "len", "(", "allowed_domain", ")", "-", "len", "(", "UrlExtractor", ".", "get_allowed_domain", ...
Determines the domain's subdomains. :param str url: the url to extract any subdomains from :return str: subdomains of url
[ "Determines", "the", "domain", "s", "subdomains", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L45-L54
train
fhamborg/news-please
newsplease/helper_classes/url_extractor.py
UrlExtractor.follow_redirects
def follow_redirects(url): """ Get's the url actual address by following forwards :param str url: the url to work on :return str: actual address of url """ opener = urllib2.build_opener(urllib2.HTTPRedirectHandler) return opener.open(url).url
python
def follow_redirects(url): """ Get's the url actual address by following forwards :param str url: the url to work on :return str: actual address of url """ opener = urllib2.build_opener(urllib2.HTTPRedirectHandler) return opener.open(url).url
[ "def", "follow_redirects", "(", "url", ")", ":", "opener", "=", "urllib2", ".", "build_opener", "(", "urllib2", ".", "HTTPRedirectHandler", ")", "return", "opener", ".", "open", "(", "url", ")", ".", "url" ]
Get's the url actual address by following forwards :param str url: the url to work on :return str: actual address of url
[ "Get", "s", "the", "url", "actual", "address", "by", "following", "forwards" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L57-L65
train
fhamborg/news-please
newsplease/helper_classes/url_extractor.py
UrlExtractor.get_sitemap_url
def get_sitemap_url(url, allow_subdomains): """ Determines the domain's robot.txt :param str url: the url to work on :param bool allow_subdomains: Determines if the robot.txt may be the subdomain's :return: the robot.txt's address :r...
python
def get_sitemap_url(url, allow_subdomains): """ Determines the domain's robot.txt :param str url: the url to work on :param bool allow_subdomains: Determines if the robot.txt may be the subdomain's :return: the robot.txt's address :r...
[ "def", "get_sitemap_url", "(", "url", ",", "allow_subdomains", ")", ":", "if", "allow_subdomains", ":", "redirect", "=", "UrlExtractor", ".", "follow_redirects", "(", "\"http://\"", "+", "UrlExtractor", ".", "get_allowed_domain", "(", "url", ")", ")", "else", ":...
Determines the domain's robot.txt :param str url: the url to work on :param bool allow_subdomains: Determines if the robot.txt may be the subdomain's :return: the robot.txt's address :raises Exception: if there's no robot.txt on the site's domain
[ "Determines", "the", "domain", "s", "robot", ".", "txt" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L68-L107
train
fhamborg/news-please
newsplease/helper_classes/url_extractor.py
UrlExtractor.sitemap_check
def sitemap_check(url): """ Sitemap-Crawler are supported by every site which have a Sitemap set in the robots.txt. :param str url: the url to work on :return bool: Determines if Sitemap is set in the site's robots.txt """ response = urllib2.urlopen(UrlExtractor....
python
def sitemap_check(url): """ Sitemap-Crawler are supported by every site which have a Sitemap set in the robots.txt. :param str url: the url to work on :return bool: Determines if Sitemap is set in the site's robots.txt """ response = urllib2.urlopen(UrlExtractor....
[ "def", "sitemap_check", "(", "url", ")", ":", "response", "=", "urllib2", ".", "urlopen", "(", "UrlExtractor", ".", "get_sitemap_url", "(", "url", ",", "True", ")", ")", "# Check if \"Sitemap\" is set", "return", "\"Sitemap:\"", "in", "response", ".", "read", ...
Sitemap-Crawler are supported by every site which have a Sitemap set in the robots.txt. :param str url: the url to work on :return bool: Determines if Sitemap is set in the site's robots.txt
[ "Sitemap", "-", "Crawler", "are", "supported", "by", "every", "site", "which", "have", "a", "Sitemap", "set", "in", "the", "robots", ".", "txt", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L110-L121
train
fhamborg/news-please
newsplease/helper_classes/url_extractor.py
UrlExtractor.get_url_directory_string
def get_url_directory_string(url): """ Determines the url's directory string. :param str url: the url to extract the directory string from :return str: the directory string on the server """ domain = UrlExtractor.get_allowed_domain(url) splitted_url = url.split(...
python
def get_url_directory_string(url): """ Determines the url's directory string. :param str url: the url to extract the directory string from :return str: the directory string on the server """ domain = UrlExtractor.get_allowed_domain(url) splitted_url = url.split(...
[ "def", "get_url_directory_string", "(", "url", ")", ":", "domain", "=", "UrlExtractor", ".", "get_allowed_domain", "(", "url", ")", "splitted_url", "=", "url", ".", "split", "(", "'/'", ")", "# the following commented list comprehension could replace", "# the following ...
Determines the url's directory string. :param str url: the url to extract the directory string from :return str: the directory string on the server
[ "Determines", "the", "url", "s", "directory", "string", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L149-L172
train
fhamborg/news-please
newsplease/helper_classes/url_extractor.py
UrlExtractor.get_url_file_name
def get_url_file_name(url): """ Determines the url's file name. :param str url: the url to extract the file name from :return str: the filename (without the file extension) on the server """ url_root_ext = os.path.splitext(url) if len(url_root_ext[1]) <= MAX_FIL...
python
def get_url_file_name(url): """ Determines the url's file name. :param str url: the url to extract the file name from :return str: the filename (without the file extension) on the server """ url_root_ext = os.path.splitext(url) if len(url_root_ext[1]) <= MAX_FIL...
[ "def", "get_url_file_name", "(", "url", ")", ":", "url_root_ext", "=", "os", ".", "path", ".", "splitext", "(", "url", ")", "if", "len", "(", "url_root_ext", "[", "1", "]", ")", "<=", "MAX_FILE_EXTENSION_LENGTH", ":", "return", "os", ".", "path", ".", ...
Determines the url's file name. :param str url: the url to extract the file name from :return str: the filename (without the file extension) on the server
[ "Determines", "the", "url", "s", "file", "name", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L175-L187
train
fhamborg/news-please
newsplease/config.py
CrawlerConfig.load_config
def load_config(self): """ Loads the config-file """ self.__config = {} # Parse sections, its options and put it in self.config. for section in self.sections: self.__config[section] = {} options = self.parser.options(section) # Parse...
python
def load_config(self): """ Loads the config-file """ self.__config = {} # Parse sections, its options and put it in self.config. for section in self.sections: self.__config[section] = {} options = self.parser.options(section) # Parse...
[ "def", "load_config", "(", "self", ")", ":", "self", ".", "__config", "=", "{", "}", "# Parse sections, its options and put it in self.config.", "for", "section", "in", "self", ".", "sections", ":", "self", ".", "__config", "[", "section", "]", "=", "{", "}", ...
Loads the config-file
[ "Loads", "the", "config", "-", "file" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/config.py#L95-L134
train
fhamborg/news-please
newsplease/config.py
CrawlerConfig.handle_logging
def handle_logging(self): """ To allow devs to log as early as possible, logging will already be handled here """ configure_logging(self.get_scrapy_options()) # Disable duplicates self.__scrapy_options["LOG_ENABLED"] = False # Now, after log-level is co...
python
def handle_logging(self): """ To allow devs to log as early as possible, logging will already be handled here """ configure_logging(self.get_scrapy_options()) # Disable duplicates self.__scrapy_options["LOG_ENABLED"] = False # Now, after log-level is co...
[ "def", "handle_logging", "(", "self", ")", ":", "configure_logging", "(", "self", ".", "get_scrapy_options", "(", ")", ")", "# Disable duplicates", "self", ".", "__scrapy_options", "[", "\"LOG_ENABLED\"", "]", "=", "False", "# Now, after log-level is correctly set, lets...
To allow devs to log as early as possible, logging will already be handled here
[ "To", "allow", "devs", "to", "log", "as", "early", "as", "possible", "logging", "will", "already", "be", "handled", "here" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/config.py#L148-L166
train
fhamborg/news-please
newsplease/config.py
CrawlerConfig.option
def option(self, option): """ Gets the option, set_section needs to be set before. :param option (string): The option to get. :return mixed: The option from from the config. """ if self.__current_section is None: raise RuntimeError('No section set in option-g...
python
def option(self, option): """ Gets the option, set_section needs to be set before. :param option (string): The option to get. :return mixed: The option from from the config. """ if self.__current_section is None: raise RuntimeError('No section set in option-g...
[ "def", "option", "(", "self", ",", "option", ")", ":", "if", "self", ".", "__current_section", "is", "None", ":", "raise", "RuntimeError", "(", "'No section set in option-getting'", ")", "return", "self", ".", "__config", "[", "self", ".", "__current_section", ...
Gets the option, set_section needs to be set before. :param option (string): The option to get. :return mixed: The option from from the config.
[ "Gets", "the", "option", "set_section", "needs", "to", "be", "set", "before", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/config.py#L194-L203
train
fhamborg/news-please
newsplease/config.py
JsonConfig.get_url_array
def get_url_array(self): """ Get all url-objects in an array :return sites (array): The sites from the JSON-file """ urlarray = [] for urlobjects in self.__json_object["base_urls"]: urlarray.append(urlobjects["url"]) return urlarray
python
def get_url_array(self): """ Get all url-objects in an array :return sites (array): The sites from the JSON-file """ urlarray = [] for urlobjects in self.__json_object["base_urls"]: urlarray.append(urlobjects["url"]) return urlarray
[ "def", "get_url_array", "(", "self", ")", ":", "urlarray", "=", "[", "]", "for", "urlobjects", "in", "self", ".", "__json_object", "[", "\"base_urls\"", "]", ":", "urlarray", ".", "append", "(", "urlobjects", "[", "\"url\"", "]", ")", "return", "urlarray" ...
Get all url-objects in an array :return sites (array): The sites from the JSON-file
[ "Get", "all", "url", "-", "objects", "in", "an", "array" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/config.py#L293-L302
train
fhamborg/news-please
newsplease/pipeline/extractor/comparer/comparer_title.py
ComparerTitle.find_matches
def find_matches(self, list_title): """Checks if there are any matches between extracted titles. :param list_title: A list, the extracted titles saved in a list :return: A list, the matched titles """ list_title_matches = [] # Generate every possible tuple of titles and ...
python
def find_matches(self, list_title): """Checks if there are any matches between extracted titles. :param list_title: A list, the extracted titles saved in a list :return: A list, the matched titles """ list_title_matches = [] # Generate every possible tuple of titles and ...
[ "def", "find_matches", "(", "self", ",", "list_title", ")", ":", "list_title_matches", "=", "[", "]", "# Generate every possible tuple of titles and safe the matched string in a list.", "for", "a", ",", "b", ",", "in", "itertools", ".", "combinations", "(", "list_title"...
Checks if there are any matches between extracted titles. :param list_title: A list, the extracted titles saved in a list :return: A list, the matched titles
[ "Checks", "if", "there", "are", "any", "matches", "between", "extracted", "titles", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_title.py#L7-L19
train
fhamborg/news-please
newsplease/pipeline/extractor/comparer/comparer_title.py
ComparerTitle.extract_match
def extract_match(self, list_title_matches): """Extract the title with the most matches from the list. :param list_title_matches: A list, the extracted titles which match with others :return: A string, the most frequently extracted title. """ # Create a set of the extracted titl...
python
def extract_match(self, list_title_matches): """Extract the title with the most matches from the list. :param list_title_matches: A list, the extracted titles which match with others :return: A string, the most frequently extracted title. """ # Create a set of the extracted titl...
[ "def", "extract_match", "(", "self", ",", "list_title_matches", ")", ":", "# Create a set of the extracted titles", "list_title_matches_set", "=", "set", "(", "list_title_matches", ")", "list_title_count", "=", "[", "]", "# Count how often a title was matched and safe as tuple ...
Extract the title with the most matches from the list. :param list_title_matches: A list, the extracted titles which match with others :return: A string, the most frequently extracted title.
[ "Extract", "the", "title", "with", "the", "most", "matches", "from", "the", "list", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_title.py#L21-L38
train
fhamborg/news-please
newsplease/pipeline/extractor/comparer/comparer_title.py
ComparerTitle.extract
def extract(self, item, list_article_candidate): """Compares the extracted titles. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely title """ ...
python
def extract(self, item, list_article_candidate): """Compares the extracted titles. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely title """ ...
[ "def", "extract", "(", "self", ",", "item", ",", "list_article_candidate", ")", ":", "list_title", "=", "[", "]", "# Save every title from the candidates in list_title.", "for", "article_candidate", "in", "list_article_candidate", ":", "if", "article_candidate", ".", "t...
Compares the extracted titles. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely title
[ "Compares", "the", "extracted", "titles", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_title.py#L53-L82
train
fhamborg/news-please
newsplease/__main__.py
cli
def cli(cfg_file_path, resume, reset_elasticsearch, reset_mysql, reset_json, reset_all, no_confirm): "A generic news crawler and extractor." if reset_all: reset_elasticsearch = True reset_json = True reset_mysql = True if cfg_file_path and not cfg_file_path.endswith(os.path.sep): ...
python
def cli(cfg_file_path, resume, reset_elasticsearch, reset_mysql, reset_json, reset_all, no_confirm): "A generic news crawler and extractor." if reset_all: reset_elasticsearch = True reset_json = True reset_mysql = True if cfg_file_path and not cfg_file_path.endswith(os.path.sep): ...
[ "def", "cli", "(", "cfg_file_path", ",", "resume", ",", "reset_elasticsearch", ",", "reset_mysql", ",", "reset_json", ",", "reset_all", ",", "no_confirm", ")", ":", "if", "reset_all", ":", "reset_elasticsearch", "=", "True", "reset_json", "=", "True", "reset_mys...
A generic news crawler and extractor.
[ "A", "generic", "news", "crawler", "and", "extractor", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L634-L645
train
fhamborg/news-please
newsplease/__main__.py
NewsPleaseLauncher.manage_crawlers
def manage_crawlers(self): """ Manages all crawlers, threads and limites the number of parallel running threads. """ sites = self.json.get_site_objects() for index, site in enumerate(sites): if "daemonize" in site: self.daemon_list.add_daemon(i...
python
def manage_crawlers(self): """ Manages all crawlers, threads and limites the number of parallel running threads. """ sites = self.json.get_site_objects() for index, site in enumerate(sites): if "daemonize" in site: self.daemon_list.add_daemon(i...
[ "def", "manage_crawlers", "(", "self", ")", ":", "sites", "=", "self", ".", "json", ".", "get_site_objects", "(", ")", "for", "index", ",", "site", "in", "enumerate", "(", "sites", ")", ":", "if", "\"daemonize\"", "in", "site", ":", "self", ".", "daemo...
Manages all crawlers, threads and limites the number of parallel running threads.
[ "Manages", "all", "crawlers", "threads", "and", "limites", "the", "number", "of", "parallel", "running", "threads", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L152-L204
train
fhamborg/news-please
newsplease/__main__.py
NewsPleaseLauncher.manage_crawler
def manage_crawler(self): """ Manages a normal crawler thread. When a crawler finished, it loads another one if there are still sites to crawl. """ index = True self.number_of_active_crawlers += 1 while not self.shutdown and index is not None: ...
python
def manage_crawler(self): """ Manages a normal crawler thread. When a crawler finished, it loads another one if there are still sites to crawl. """ index = True self.number_of_active_crawlers += 1 while not self.shutdown and index is not None: ...
[ "def", "manage_crawler", "(", "self", ")", ":", "index", "=", "True", "self", ".", "number_of_active_crawlers", "+=", "1", "while", "not", "self", ".", "shutdown", "and", "index", "is", "not", "None", ":", "index", "=", "self", ".", "crawler_list", ".", ...
Manages a normal crawler thread. When a crawler finished, it loads another one if there are still sites to crawl.
[ "Manages", "a", "normal", "crawler", "thread", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L206-L221
train
fhamborg/news-please
newsplease/__main__.py
NewsPleaseLauncher.manage_daemon
def manage_daemon(self): """ Manages a daemonized crawler thread. Once a crawler it finished, it loads the next one. """ while not self.shutdown: # next scheduled daemon, tuple (time, index) item = self.daemon_list.get_next_item() cur = time.t...
python
def manage_daemon(self): """ Manages a daemonized crawler thread. Once a crawler it finished, it loads the next one. """ while not self.shutdown: # next scheduled daemon, tuple (time, index) item = self.daemon_list.get_next_item() cur = time.t...
[ "def", "manage_daemon", "(", "self", ")", ":", "while", "not", "self", ".", "shutdown", ":", "# next scheduled daemon, tuple (time, index)", "item", "=", "self", ".", "daemon_list", ".", "get_next_item", "(", ")", "cur", "=", "time", ".", "time", "(", ")", "...
Manages a daemonized crawler thread. Once a crawler it finished, it loads the next one.
[ "Manages", "a", "daemonized", "crawler", "thread", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L223-L237
train
fhamborg/news-please
newsplease/__main__.py
NewsPleaseLauncher.start_crawler
def start_crawler(self, index, daemonize=False): """ Starts a crawler from the input-array. :param int index: The array-index of the site :param int daemonize: Bool if the crawler is supposed to be daemonized (to delete the JOBDIR) """ call_...
python
def start_crawler(self, index, daemonize=False): """ Starts a crawler from the input-array. :param int index: The array-index of the site :param int daemonize: Bool if the crawler is supposed to be daemonized (to delete the JOBDIR) """ call_...
[ "def", "start_crawler", "(", "self", ",", "index", ",", "daemonize", "=", "False", ")", ":", "call_process", "=", "[", "sys", ".", "executable", ",", "self", ".", "__single_crawler", ",", "self", ".", "cfg_file_path", ",", "self", ".", "json_file_path", ",...
Starts a crawler from the input-array. :param int index: The array-index of the site :param int daemonize: Bool if the crawler is supposed to be daemonized (to delete the JOBDIR)
[ "Starts", "a", "crawler", "from", "the", "input", "-", "array", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L239-L261
train
fhamborg/news-please
newsplease/__main__.py
NewsPleaseLauncher.graceful_stop
def graceful_stop(self, signal_number=None, stack_frame=None): """ This function will be called when a graceful-stop is initiated. """ stop_msg = "Hard" if self.shutdown else "Graceful" if signal_number is None: self.log.info("%s stop called manually. " ...
python
def graceful_stop(self, signal_number=None, stack_frame=None): """ This function will be called when a graceful-stop is initiated. """ stop_msg = "Hard" if self.shutdown else "Graceful" if signal_number is None: self.log.info("%s stop called manually. " ...
[ "def", "graceful_stop", "(", "self", ",", "signal_number", "=", "None", ",", "stack_frame", "=", "None", ")", ":", "stop_msg", "=", "\"Hard\"", "if", "self", ".", "shutdown", "else", "\"Graceful\"", "if", "signal_number", "is", "None", ":", "self", ".", "l...
This function will be called when a graceful-stop is initiated.
[ "This", "function", "will", "be", "called", "when", "a", "graceful", "-", "stop", "is", "initiated", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L263-L279
train
fhamborg/news-please
newsplease/helper_classes/savepath_parser.py
SavepathParser.time_replacer
def time_replacer(match, timestamp): """ Transforms the timestamp to the format the regex match determines. :param str match: the regex match :param time timestamp: the timestamp to format with match.group(1) :return str: the timestamp formated with strftime the way the ...
python
def time_replacer(match, timestamp): """ Transforms the timestamp to the format the regex match determines. :param str match: the regex match :param time timestamp: the timestamp to format with match.group(1) :return str: the timestamp formated with strftime the way the ...
[ "def", "time_replacer", "(", "match", ",", "timestamp", ")", ":", "# match.group(0) = entire match", "# match.group(1) = match in braces #1", "return", "time", ".", "strftime", "(", "match", ".", "group", "(", "1", ")", ",", "time", ".", "gmtime", "(", "timestamp"...
Transforms the timestamp to the format the regex match determines. :param str match: the regex match :param time timestamp: the timestamp to format with match.group(1) :return str: the timestamp formated with strftime the way the regex-match within the first set of braces d...
[ "Transforms", "the", "timestamp", "to", "the", "format", "the", "regex", "match", "determines", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L76-L87
train
fhamborg/news-please
newsplease/helper_classes/savepath_parser.py
SavepathParser.append_md5_if_too_long
def append_md5_if_too_long(component, size): """ Trims the component if it is longer than size and appends the component's md5. Total must be of length size. :param str component: component to work on :param int size: component's size limit :return str: component and app...
python
def append_md5_if_too_long(component, size): """ Trims the component if it is longer than size and appends the component's md5. Total must be of length size. :param str component: component to work on :param int size: component's size limit :return str: component and app...
[ "def", "append_md5_if_too_long", "(", "component", ",", "size", ")", ":", "if", "len", "(", "component", ")", ">", "size", ":", "if", "size", ">", "32", ":", "component_size", "=", "size", "-", "32", "-", "1", "return", "\"%s_%s\"", "%", "(", "componen...
Trims the component if it is longer than size and appends the component's md5. Total must be of length size. :param str component: component to work on :param int size: component's size limit :return str: component and appended md5 trimmed to be of length size
[ "Trims", "the", "component", "if", "it", "is", "longer", "than", "size", "and", "appends", "the", "component", "s", "md5", ".", "Total", "must", "be", "of", "length", "size", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L90-L108
train
fhamborg/news-please
newsplease/helper_classes/savepath_parser.py
SavepathParser.remove_not_allowed_chars
def remove_not_allowed_chars(savepath): """ Removes invalid filepath characters from the savepath. :param str savepath: the savepath to work on :return str: the savepath without invalid filepath characters """ split_savepath = os.path.splitdrive(savepath) # https...
python
def remove_not_allowed_chars(savepath): """ Removes invalid filepath characters from the savepath. :param str savepath: the savepath to work on :return str: the savepath without invalid filepath characters """ split_savepath = os.path.splitdrive(savepath) # https...
[ "def", "remove_not_allowed_chars", "(", "savepath", ")", ":", "split_savepath", "=", "os", ".", "path", ".", "splitdrive", "(", "savepath", ")", "# https://msdn.microsoft.com/en-us/library/aa365247.aspx", "savepath_without_invalid_chars", "=", "re", ".", "sub", "(", "r'...
Removes invalid filepath characters from the savepath. :param str savepath: the savepath to work on :return str: the savepath without invalid filepath characters
[ "Removes", "invalid", "filepath", "characters", "from", "the", "savepath", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L219-L230
train
fhamborg/news-please
newsplease/helper_classes/savepath_parser.py
SavepathParser.get_abs_path_static
def get_abs_path_static(savepath, relative_to_path): """ Figures out the savepath's absolute version. :param str savepath: the savepath to return an absolute version of :param str relative_to_path: the file path this savepath should be relative to ...
python
def get_abs_path_static(savepath, relative_to_path): """ Figures out the savepath's absolute version. :param str savepath: the savepath to return an absolute version of :param str relative_to_path: the file path this savepath should be relative to ...
[ "def", "get_abs_path_static", "(", "savepath", ",", "relative_to_path", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "savepath", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "savepath", ")", "else", ":", "return", "os", ".", "pa...
Figures out the savepath's absolute version. :param str savepath: the savepath to return an absolute version of :param str relative_to_path: the file path this savepath should be relative to :return str: absolute version of savepath
[ "Figures", "out", "the", "savepath", "s", "absolute", "version", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L233-L247
train
fhamborg/news-please
newsplease/helper_classes/savepath_parser.py
SavepathParser.get_base_path
def get_base_path(path): """ Determines the longest possible beginning of a path that does not contain a %-Symbol. /this/is/a/pa%th would become /this/is/a :param str path: the path to get the base from :return: the path's base """ if "%" not in path: ...
python
def get_base_path(path): """ Determines the longest possible beginning of a path that does not contain a %-Symbol. /this/is/a/pa%th would become /this/is/a :param str path: the path to get the base from :return: the path's base """ if "%" not in path: ...
[ "def", "get_base_path", "(", "path", ")", ":", "if", "\"%\"", "not", "in", "path", ":", "return", "path", "path", "=", "os", ".", "path", ".", "split", "(", "path", ")", "[", "0", "]", "while", "\"%\"", "in", "path", ":", "path", "=", "os", ".", ...
Determines the longest possible beginning of a path that does not contain a %-Symbol. /this/is/a/pa%th would become /this/is/a :param str path: the path to get the base from :return: the path's base
[ "Determines", "the", "longest", "possible", "beginning", "of", "a", "path", "that", "does", "not", "contain", "a", "%", "-", "Symbol", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L260-L278
train
fhamborg/news-please
newsplease/helper_classes/savepath_parser.py
SavepathParser.get_max_url_file_name_length
def get_max_url_file_name_length(savepath): """ Determines the max length for any max... parts. :param str savepath: absolute savepath to work on :return: max. allowed number of chars for any of the max... parts """ number_occurrences = savepath.count('%max_url_file_name...
python
def get_max_url_file_name_length(savepath): """ Determines the max length for any max... parts. :param str savepath: absolute savepath to work on :return: max. allowed number of chars for any of the max... parts """ number_occurrences = savepath.count('%max_url_file_name...
[ "def", "get_max_url_file_name_length", "(", "savepath", ")", ":", "number_occurrences", "=", "savepath", ".", "count", "(", "'%max_url_file_name'", ")", "number_occurrences", "+=", "savepath", ".", "count", "(", "'%appendmd5_max_url_file_name'", ")", "savepath_copy", "=...
Determines the max length for any max... parts. :param str savepath: absolute savepath to work on :return: max. allowed number of chars for any of the max... parts
[ "Determines", "the", "max", "length", "for", "any", "max", "...", "parts", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L295-L316
train
fhamborg/news-please
newsplease/pipeline/extractor/extractors/readability_extractor.py
ReadabilityExtractor.extract
def extract(self, item): """Creates an readability document and returns an ArticleCandidate containing article title and text. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data. """ doc = Document(deepcopy(item['spider_resp...
python
def extract(self, item): """Creates an readability document and returns an ArticleCandidate containing article title and text. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data. """ doc = Document(deepcopy(item['spider_resp...
[ "def", "extract", "(", "self", ",", "item", ")", ":", "doc", "=", "Document", "(", "deepcopy", "(", "item", "[", "'spider_response'", "]", ".", "body", ")", ")", "description", "=", "doc", ".", "summary", "(", ")", "article_candidate", "=", "ArticleCandi...
Creates an readability document and returns an ArticleCandidate containing article title and text. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data.
[ "Creates", "an", "readability", "document", "and", "returns", "an", "ArticleCandidate", "containing", "article", "title", "and", "text", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/extractors/readability_extractor.py#L18-L38
train
fhamborg/news-please
newsplease/pipeline/extractor/article_extractor.py
Extractor.extract
def extract(self, item): """Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results. :param item: NewscrawlerItem to be processed. :return: An updated NewscrawlerItem including the results of the extraction """ article_candidates = [] ...
python
def extract(self, item): """Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results. :param item: NewscrawlerItem to be processed. :return: An updated NewscrawlerItem including the results of the extraction """ article_candidates = [] ...
[ "def", "extract", "(", "self", ",", "item", ")", ":", "article_candidates", "=", "[", "]", "for", "extractor", "in", "self", ".", "extractor_list", ":", "article_candidates", ".", "append", "(", "extractor", ".", "extract", "(", "item", ")", ")", "article_...
Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results. :param item: NewscrawlerItem to be processed. :return: An updated NewscrawlerItem including the results of the extraction
[ "Runs", "the", "HTML", "-", "response", "trough", "a", "list", "of", "initialized", "extractors", "a", "cleaner", "and", "compares", "the", "results", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/article_extractor.py#L43-L66
train
fhamborg/news-please
newsplease/helper_classes/parse_crawler.py
ParseCrawler.pass_to_pipeline_if_article
def pass_to_pipeline_if_article( self, response, source_domain, original_url, rss_title=None ): """ Responsible for passing a NewscrawlerItem to the pipeline if the response contains an article. :param obj response: the scr...
python
def pass_to_pipeline_if_article( self, response, source_domain, original_url, rss_title=None ): """ Responsible for passing a NewscrawlerItem to the pipeline if the response contains an article. :param obj response: the scr...
[ "def", "pass_to_pipeline_if_article", "(", "self", ",", "response", ",", "source_domain", ",", "original_url", ",", "rss_title", "=", "None", ")", ":", "if", "self", ".", "helper", ".", "heuristics", ".", "is_article", "(", "response", ",", "original_url", ")"...
Responsible for passing a NewscrawlerItem to the pipeline if the response contains an article. :param obj response: the scrapy response to work on :param str source_domain: the response's domain as set for the crawler :param str original_url: the url set in the json file :param ...
[ "Responsible", "for", "passing", "a", "NewscrawlerItem", "to", "the", "pipeline", "if", "the", "response", "contains", "an", "article", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/parse_crawler.py#L27-L46
train
fhamborg/news-please
newsplease/helper_classes/parse_crawler.py
ParseCrawler.recursive_requests
def recursive_requests(response, spider, ignore_regex='', ignore_file_extensions='pdf'): """ Manages recursive requests. Determines urls to recursivly crawl if they do not match certain file extensions and do not match a certain regex set in the config file. ...
python
def recursive_requests(response, spider, ignore_regex='', ignore_file_extensions='pdf'): """ Manages recursive requests. Determines urls to recursivly crawl if they do not match certain file extensions and do not match a certain regex set in the config file. ...
[ "def", "recursive_requests", "(", "response", ",", "spider", ",", "ignore_regex", "=", "''", ",", "ignore_file_extensions", "=", "'pdf'", ")", ":", "# Recursivly crawl all URLs on the current page", "# that do not point to irrelevant file types", "# or contain any of the given ig...
Manages recursive requests. Determines urls to recursivly crawl if they do not match certain file extensions and do not match a certain regex set in the config file. :param obj response: the response to extract any urls from :param obj spider: the crawler the callback should be called o...
[ "Manages", "recursive", "requests", ".", "Determines", "urls", "to", "recursivly", "crawl", "if", "they", "do", "not", "match", "certain", "file", "extensions", "and", "do", "not", "match", "a", "certain", "regex", "set", "in", "the", "config", "file", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/parse_crawler.py#L87-L112
train
fhamborg/news-please
newsplease/helper_classes/parse_crawler.py
ParseCrawler.content_type
def content_type(self, response): """ Ensures the response is of type :param obj response: The scrapy response :return bool: Determines wether the response is of the correct type """ if not re_html.match(response.headers.get('Content-Type').decode('utf-8')): ...
python
def content_type(self, response): """ Ensures the response is of type :param obj response: The scrapy response :return bool: Determines wether the response is of the correct type """ if not re_html.match(response.headers.get('Content-Type').decode('utf-8')): ...
[ "def", "content_type", "(", "self", ",", "response", ")", ":", "if", "not", "re_html", ".", "match", "(", "response", ".", "headers", ".", "get", "(", "'Content-Type'", ")", ".", "decode", "(", "'utf-8'", ")", ")", ":", "self", ".", "log", ".", "warn...
Ensures the response is of type :param obj response: The scrapy response :return bool: Determines wether the response is of the correct type
[ "Ensures", "the", "response", "is", "of", "type" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/parse_crawler.py#L114-L128
train
fhamborg/news-please
newsplease/pipeline/extractor/comparer/comparer_topimage.py
ComparerTopimage.extract
def extract(self, item, list_article_candidate): """Compares the extracted top images. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string (url), the most likely top image ...
python
def extract(self, item, list_article_candidate): """Compares the extracted top images. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string (url), the most likely top image ...
[ "def", "extract", "(", "self", ",", "item", ",", "list_article_candidate", ")", ":", "list_topimage", "=", "[", "]", "for", "article_candidate", "in", "list_article_candidate", ":", "if", "article_candidate", ".", "topimage", "is", "not", "None", ":", "# Changes...
Compares the extracted top images. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string (url), the most likely top image
[ "Compares", "the", "extracted", "top", "images", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_topimage.py#L15-L41
train
fhamborg/news-please
newsplease/pipeline/extractor/comparer/comparer_text.py
ComparerText.extract
def extract(self, item, article_candidate_list): """Compares the extracted texts. :param item: The corresponding NewscrawlerItem :param article_candidate_list: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely text """ ...
python
def extract(self, item, article_candidate_list): """Compares the extracted texts. :param item: The corresponding NewscrawlerItem :param article_candidate_list: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely text """ ...
[ "def", "extract", "(", "self", ",", "item", ",", "article_candidate_list", ")", ":", "list_text", "=", "[", "]", "# The minimal number of words a text needs to have", "min_number_words", "=", "15", "# The texts of the article candidates and the respective extractors are saved in ...
Compares the extracted texts. :param item: The corresponding NewscrawlerItem :param article_candidate_list: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely text
[ "Compares", "the", "extracted", "texts", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_text.py#L7-L79
train
fhamborg/news-please
newsplease/helper_classes/sub_classes/heuristics_manager.py
HeuristicsManager.is_article
def is_article(self, response, url): """ Tests if the given response is an article by calling and checking the heuristics set in config.cfg and sitelist.json :param obj response: The response of the site. :param str url: The base_url (needed to get the site-specific config ...
python
def is_article(self, response, url): """ Tests if the given response is an article by calling and checking the heuristics set in config.cfg and sitelist.json :param obj response: The response of the site. :param str url: The base_url (needed to get the site-specific config ...
[ "def", "is_article", "(", "self", ",", "response", ",", "url", ")", ":", "site", "=", "self", ".", "__sites_object", "[", "url", "]", "heuristics", "=", "self", ".", "__get_enabled_heuristics", "(", "url", ")", "self", ".", "log", ".", "info", "(", "\"...
Tests if the given response is an article by calling and checking the heuristics set in config.cfg and sitelist.json :param obj response: The response of the site. :param str url: The base_url (needed to get the site-specific config from the JSON-file) :return bo...
[ "Tests", "if", "the", "given", "response", "is", "an", "article", "by", "calling", "and", "checking", "the", "heuristics", "set", "in", "config", ".", "cfg", "and", "sitelist", ".", "json" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L36-L67
train
fhamborg/news-please
newsplease/helper_classes/sub_classes/heuristics_manager.py
HeuristicsManager.__get_condition
def __get_condition(self, url): """ Gets the condition for a url and validates it. :param str url: The url to get the condition for """ if self.__heuristics_condition is not None: return self.__heuristics_condition if "pass_heuristics_condition" in self.__sit...
python
def __get_condition(self, url): """ Gets the condition for a url and validates it. :param str url: The url to get the condition for """ if self.__heuristics_condition is not None: return self.__heuristics_condition if "pass_heuristics_condition" in self.__sit...
[ "def", "__get_condition", "(", "self", ",", "url", ")", ":", "if", "self", ".", "__heuristics_condition", "is", "not", "None", ":", "return", "self", ".", "__heuristics_condition", "if", "\"pass_heuristics_condition\"", "in", "self", ".", "__sites_object", "[", ...
Gets the condition for a url and validates it. :param str url: The url to get the condition for
[ "Gets", "the", "condition", "for", "a", "url", "and", "validates", "it", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L69-L110
train
fhamborg/news-please
newsplease/helper_classes/sub_classes/heuristics_manager.py
HeuristicsManager.__evaluate_result
def __evaluate_result(self, result, condition): """ Evaluates a result of a heuristic with the condition given in the config. :param mixed result: The result of the heuristic :param mixed condition: The condition string to evaluate on the result :return bool: Whether the...
python
def __evaluate_result(self, result, condition): """ Evaluates a result of a heuristic with the condition given in the config. :param mixed result: The result of the heuristic :param mixed condition: The condition string to evaluate on the result :return bool: Whether the...
[ "def", "__evaluate_result", "(", "self", ",", "result", ",", "condition", ")", ":", "# If result is bool this means, that the heuristic", "# is bool as well or has a special situation", "# (for example some condition [e.g. in config] is [not] met, thus", "# just pass it)", "if", "isin...
Evaluates a result of a heuristic with the condition given in the config. :param mixed result: The result of the heuristic :param mixed condition: The condition string to evaluate on the result :return bool: Whether the heuristic result matches the condition
[ "Evaluates", "a", "result", "of", "a", "heuristic", "with", "the", "condition", "given", "in", "the", "config", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L112-L200
train
fhamborg/news-please
newsplease/helper_classes/sub_classes/heuristics_manager.py
HeuristicsManager.__evaluation_error
def __evaluation_error(self, result, condition, throw): """Helper-method for easy error-logging""" self.log.error("Result does not match condition, dropping item. " "Result %s; Condition: %s; Throw: %s", result, condition, throw) return False
python
def __evaluation_error(self, result, condition, throw): """Helper-method for easy error-logging""" self.log.error("Result does not match condition, dropping item. " "Result %s; Condition: %s; Throw: %s", result, condition, throw) return False
[ "def", "__evaluation_error", "(", "self", ",", "result", ",", "condition", ",", "throw", ")", ":", "self", ".", "log", ".", "error", "(", "\"Result does not match condition, dropping item. \"", "\"Result %s; Condition: %s; Throw: %s\"", ",", "result", ",", "condition", ...
Helper-method for easy error-logging
[ "Helper", "-", "method", "for", "easy", "error", "-", "logging" ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L202-L207
train
fhamborg/news-please
newsplease/helper_classes/sub_classes/heuristics_manager.py
HeuristicsManager.__try_parse_number
def __try_parse_number(self, string): """Try to parse a string to a number, else return False.""" try: return int(string) except ValueError: try: return float(string) except ValueError: return False
python
def __try_parse_number(self, string): """Try to parse a string to a number, else return False.""" try: return int(string) except ValueError: try: return float(string) except ValueError: return False
[ "def", "__try_parse_number", "(", "self", ",", "string", ")", ":", "try", ":", "return", "int", "(", "string", ")", "except", "ValueError", ":", "try", ":", "return", "float", "(", "string", ")", "except", "ValueError", ":", "return", "False" ]
Try to parse a string to a number, else return False.
[ "Try", "to", "parse", "a", "string", "to", "a", "number", "else", "return", "False", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L209-L217
train
fhamborg/news-please
newsplease/helper_classes/sub_classes/heuristics_manager.py
HeuristicsManager.__get_enabled_heuristics
def __get_enabled_heuristics(self, url): """ Get the enabled heuristics for a site, merging the default and the overwrite together. The config will only be read once and the merged site-config will be cached. :param str url: The url to get the heuristics for. """...
python
def __get_enabled_heuristics(self, url): """ Get the enabled heuristics for a site, merging the default and the overwrite together. The config will only be read once and the merged site-config will be cached. :param str url: The url to get the heuristics for. """...
[ "def", "__get_enabled_heuristics", "(", "self", ",", "url", ")", ":", "if", "url", "in", "self", ".", "__sites_heuristics", ":", "return", "self", ".", "__sites_heuristics", "[", "url", "]", "site", "=", "self", ".", "__sites_object", "[", "url", "]", "heu...
Get the enabled heuristics for a site, merging the default and the overwrite together. The config will only be read once and the merged site-config will be cached. :param str url: The url to get the heuristics for.
[ "Get", "the", "enabled", "heuristics", "for", "a", "site", "merging", "the", "default", "and", "the", "overwrite", "together", ".", "The", "config", "will", "only", "be", "read", "once", "and", "the", "merged", "site", "-", "config", "will", "be", "cached"...
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L219-L245
train
fhamborg/news-please
newsplease/pipeline/extractor/extractors/abstract_extractor.py
AbstractExtractor.extract
def extract(self, item): """Executes all implemented functions on the given article and returns an object containing the recovered data. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data. """ article_candidate = Art...
python
def extract(self, item): """Executes all implemented functions on the given article and returns an object containing the recovered data. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data. """ article_candidate = Art...
[ "def", "extract", "(", "self", ",", "item", ")", ":", "article_candidate", "=", "ArticleCandidate", "(", ")", "article_candidate", ".", "extractor", "=", "self", ".", "_name", "(", ")", "article_candidate", ".", "title", "=", "self", ".", "_title", "(", "i...
Executes all implemented functions on the given article and returns an object containing the recovered data. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data.
[ "Executes", "all", "implemented", "functions", "on", "the", "given", "article", "and", "returns", "an", "object", "containing", "the", "recovered", "data", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/extractors/abstract_extractor.py#L48-L66
train
fhamborg/news-please
newsplease/pipeline/extractor/extractors/newspaper_extractor.py
NewspaperExtractor.extract
def extract(self, item): """Creates an instance of Article without a Download and returns an ArticleCandidate with the results of parsing the HTML-Code. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data. """ article_...
python
def extract(self, item): """Creates an instance of Article without a Download and returns an ArticleCandidate with the results of parsing the HTML-Code. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data. """ article_...
[ "def", "extract", "(", "self", ",", "item", ")", ":", "article_candidate", "=", "ArticleCandidate", "(", ")", "article_candidate", ".", "extractor", "=", "self", ".", "_name", "(", ")", "article", "=", "Article", "(", "''", ")", "article", ".", "set_html",...
Creates an instance of Article without a Download and returns an ArticleCandidate with the results of parsing the HTML-Code. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data.
[ "Creates", "an", "instance", "of", "Article", "without", "a", "Download", "and", "returns", "an", "ArticleCandidate", "with", "the", "results", "of", "parsing", "the", "HTML", "-", "Code", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/extractors/newspaper_extractor.py#L18-L44
train
fhamborg/news-please
newsplease/pipeline/extractor/comparer/comparer_author.py
ComparerAuthor.extract
def extract(self, item, list_article_candidate): """Compares the extracted authors. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely authors """...
python
def extract(self, item, list_article_candidate): """Compares the extracted authors. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely authors """...
[ "def", "extract", "(", "self", ",", "item", ",", "list_article_candidate", ")", ":", "list_author", "=", "[", "]", "# The authors of the ArticleCandidates and the respective extractors are saved in a tuple in list_author.", "for", "article_candidate", "in", "list_article_candidat...
Compares the extracted authors. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely authors
[ "Compares", "the", "extracted", "authors", "." ]
731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_author.py#L4-L29
train
GNS3/gns3-server
gns3server/utils/asyncio/serial.py
_asyncio_open_serial_windows
def _asyncio_open_serial_windows(path): """ Open a windows named pipe :returns: An IO like object """ try: yield from wait_for_named_pipe_creation(path) except asyncio.TimeoutError: raise NodeError('Pipe file "{}" is missing'.format(path)) return WindowsPipe(path)
python
def _asyncio_open_serial_windows(path): """ Open a windows named pipe :returns: An IO like object """ try: yield from wait_for_named_pipe_creation(path) except asyncio.TimeoutError: raise NodeError('Pipe file "{}" is missing'.format(path)) return WindowsPipe(path)
[ "def", "_asyncio_open_serial_windows", "(", "path", ")", ":", "try", ":", "yield", "from", "wait_for_named_pipe_creation", "(", "path", ")", "except", "asyncio", ".", "TimeoutError", ":", "raise", "NodeError", "(", "'Pipe file \"{}\" is missing'", ".", "format", "("...
Open a windows named pipe :returns: An IO like object
[ "Open", "a", "windows", "named", "pipe" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/serial.py#L99-L110
train
GNS3/gns3-server
gns3server/utils/asyncio/serial.py
_asyncio_open_serial_unix
def _asyncio_open_serial_unix(path): """ Open a unix socket or a windows named pipe :returns: An IO like object """ try: # wait for VM to create the pipe file. yield from wait_for_file_creation(path) except asyncio.TimeoutError: raise NodeError('Pipe file "{}" is missin...
python
def _asyncio_open_serial_unix(path): """ Open a unix socket or a windows named pipe :returns: An IO like object """ try: # wait for VM to create the pipe file. yield from wait_for_file_creation(path) except asyncio.TimeoutError: raise NodeError('Pipe file "{}" is missin...
[ "def", "_asyncio_open_serial_unix", "(", "path", ")", ":", "try", ":", "# wait for VM to create the pipe file.", "yield", "from", "wait_for_file_creation", "(", "path", ")", "except", "asyncio", ".", "TimeoutError", ":", "raise", "NodeError", "(", "'Pipe file \"{}\" is ...
Open a unix socket or a windows named pipe :returns: An IO like object
[ "Open", "a", "unix", "socket", "or", "a", "windows", "named", "pipe" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/serial.py#L114-L132
train
GNS3/gns3-server
gns3server/controller/udp_link.py
UDPLink.create
def create(self): """ Create the link on the nodes """ node1 = self._nodes[0]["node"] adapter_number1 = self._nodes[0]["adapter_number"] port_number1 = self._nodes[0]["port_number"] node2 = self._nodes[1]["node"] adapter_number2 = self._nodes[1]["adapter_...
python
def create(self): """ Create the link on the nodes """ node1 = self._nodes[0]["node"] adapter_number1 = self._nodes[0]["adapter_number"] port_number1 = self._nodes[0]["port_number"] node2 = self._nodes[1]["node"] adapter_number2 = self._nodes[1]["adapter_...
[ "def", "create", "(", "self", ")", ":", "node1", "=", "self", ".", "_nodes", "[", "0", "]", "[", "\"node\"", "]", "adapter_number1", "=", "self", ".", "_nodes", "[", "0", "]", "[", "\"adapter_number\"", "]", "port_number1", "=", "self", ".", "_nodes", ...
Create the link on the nodes
[ "Create", "the", "link", "on", "the", "nodes" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L41-L96
train
GNS3/gns3-server
gns3server/controller/udp_link.py
UDPLink.delete
def delete(self): """ Delete the link and free the resources """ if not self._created: return try: node1 = self._nodes[0]["node"] adapter_number1 = self._nodes[0]["adapter_number"] port_number1 = self._nodes[0]["port_number"] ...
python
def delete(self): """ Delete the link and free the resources """ if not self._created: return try: node1 = self._nodes[0]["node"] adapter_number1 = self._nodes[0]["adapter_number"] port_number1 = self._nodes[0]["port_number"] ...
[ "def", "delete", "(", "self", ")", ":", "if", "not", "self", ".", "_created", ":", "return", "try", ":", "node1", "=", "self", ".", "_nodes", "[", "0", "]", "[", "\"node\"", "]", "adapter_number1", "=", "self", ".", "_nodes", "[", "0", "]", "[", ...
Delete the link and free the resources
[ "Delete", "the", "link", "and", "free", "the", "resources" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L118-L147
train
GNS3/gns3-server
gns3server/controller/udp_link.py
UDPLink.start_capture
def start_capture(self, data_link_type="DLT_EN10MB", capture_file_name=None): """ Start capture on a link """ if not capture_file_name: capture_file_name = self.default_capture_file_name() self._capture_node = self._choose_capture_side() data = { "...
python
def start_capture(self, data_link_type="DLT_EN10MB", capture_file_name=None): """ Start capture on a link """ if not capture_file_name: capture_file_name = self.default_capture_file_name() self._capture_node = self._choose_capture_side() data = { "...
[ "def", "start_capture", "(", "self", ",", "data_link_type", "=", "\"DLT_EN10MB\"", ",", "capture_file_name", "=", "None", ")", ":", "if", "not", "capture_file_name", ":", "capture_file_name", "=", "self", ".", "default_capture_file_name", "(", ")", "self", ".", ...
Start capture on a link
[ "Start", "capture", "on", "a", "link" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L150-L162
train
GNS3/gns3-server
gns3server/controller/udp_link.py
UDPLink.stop_capture
def stop_capture(self): """ Stop capture on a link """ if self._capture_node: yield from self._capture_node["node"].post("/adapters/{adapter_number}/ports/{port_number}/stop_capture".format(adapter_number=self._capture_node["adapter_number"], port_number=self._capture_node["p...
python
def stop_capture(self): """ Stop capture on a link """ if self._capture_node: yield from self._capture_node["node"].post("/adapters/{adapter_number}/ports/{port_number}/stop_capture".format(adapter_number=self._capture_node["adapter_number"], port_number=self._capture_node["p...
[ "def", "stop_capture", "(", "self", ")", ":", "if", "self", ".", "_capture_node", ":", "yield", "from", "self", ".", "_capture_node", "[", "\"node\"", "]", ".", "post", "(", "\"/adapters/{adapter_number}/ports/{port_number}/stop_capture\"", ".", "format", "(", "ad...
Stop capture on a link
[ "Stop", "capture", "on", "a", "link" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L165-L172
train
GNS3/gns3-server
gns3server/controller/udp_link.py
UDPLink._choose_capture_side
def _choose_capture_side(self): """ Run capture on the best candidate. The ideal candidate is a node who on controller server and always running (capture will not be cut off) :returns: Node where the capture should run """ ALWAYS_RUNNING_NODES_TYPE = ("cloud", ...
python
def _choose_capture_side(self): """ Run capture on the best candidate. The ideal candidate is a node who on controller server and always running (capture will not be cut off) :returns: Node where the capture should run """ ALWAYS_RUNNING_NODES_TYPE = ("cloud", ...
[ "def", "_choose_capture_side", "(", "self", ")", ":", "ALWAYS_RUNNING_NODES_TYPE", "=", "(", "\"cloud\"", ",", "\"nat\"", ",", "\"ethernet_switch\"", ",", "\"ethernet_hub\"", ")", "for", "node", "in", "self", ".", "_nodes", ":", "if", "node", "[", "\"node\"", ...
Run capture on the best candidate. The ideal candidate is a node who on controller server and always running (capture will not be cut off) :returns: Node where the capture should run
[ "Run", "capture", "on", "the", "best", "candidate", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L174-L202
train
GNS3/gns3-server
gns3server/controller/udp_link.py
UDPLink.read_pcap_from_source
def read_pcap_from_source(self): """ Return a FileStream of the Pcap from the compute node """ if self._capture_node: compute = self._capture_node["node"].compute return compute.stream_file(self._project, "tmp/captures/" + self._capture_file_name)
python
def read_pcap_from_source(self): """ Return a FileStream of the Pcap from the compute node """ if self._capture_node: compute = self._capture_node["node"].compute return compute.stream_file(self._project, "tmp/captures/" + self._capture_file_name)
[ "def", "read_pcap_from_source", "(", "self", ")", ":", "if", "self", ".", "_capture_node", ":", "compute", "=", "self", ".", "_capture_node", "[", "\"node\"", "]", ".", "compute", "return", "compute", ".", "stream_file", "(", "self", ".", "_project", ",", ...
Return a FileStream of the Pcap from the compute node
[ "Return", "a", "FileStream", "of", "the", "Pcap", "from", "the", "compute", "node" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L205-L211
train
GNS3/gns3-server
gns3server/controller/udp_link.py
UDPLink.node_updated
def node_updated(self, node): """ Called when a node member of the link is updated """ if self._capture_node and node == self._capture_node["node"] and node.status != "started": yield from self.stop_capture()
python
def node_updated(self, node): """ Called when a node member of the link is updated """ if self._capture_node and node == self._capture_node["node"] and node.status != "started": yield from self.stop_capture()
[ "def", "node_updated", "(", "self", ",", "node", ")", ":", "if", "self", ".", "_capture_node", "and", "node", "==", "self", ".", "_capture_node", "[", "\"node\"", "]", "and", "node", ".", "status", "!=", "\"started\"", ":", "yield", "from", "self", ".", ...
Called when a node member of the link is updated
[ "Called", "when", "a", "node", "member", "of", "the", "link", "is", "updated" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L214-L219
train
GNS3/gns3-server
gns3server/utils/vmnet.py
parse_networking_file
def parse_networking_file(): """ Parse the VMware networking file. """ pairs = dict() allocated_subnets = [] try: with open(VMWARE_NETWORKING_FILE, "r", encoding="utf-8") as f: version = f.readline() for line in f.read().splitlines(): try: ...
python
def parse_networking_file(): """ Parse the VMware networking file. """ pairs = dict() allocated_subnets = [] try: with open(VMWARE_NETWORKING_FILE, "r", encoding="utf-8") as f: version = f.readline() for line in f.read().splitlines(): try: ...
[ "def", "parse_networking_file", "(", ")", ":", "pairs", "=", "dict", "(", ")", "allocated_subnets", "=", "[", "]", "try", ":", "with", "open", "(", "VMWARE_NETWORKING_FILE", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "version", ...
Parse the VMware networking file.
[ "Parse", "the", "VMware", "networking", "file", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/vmnet.py#L39-L61
train
GNS3/gns3-server
gns3server/utils/vmnet.py
write_networking_file
def write_networking_file(version, pairs): """ Write the VMware networking file. """ vmnets = OrderedDict(sorted(pairs.items(), key=lambda t: t[0])) try: with open(VMWARE_NETWORKING_FILE, "w", encoding="utf-8") as f: f.write(version) for key, value in vmnets.items():...
python
def write_networking_file(version, pairs): """ Write the VMware networking file. """ vmnets = OrderedDict(sorted(pairs.items(), key=lambda t: t[0])) try: with open(VMWARE_NETWORKING_FILE, "w", encoding="utf-8") as f: f.write(version) for key, value in vmnets.items():...
[ "def", "write_networking_file", "(", "version", ",", "pairs", ")", ":", "vmnets", "=", "OrderedDict", "(", "sorted", "(", "pairs", ".", "items", "(", ")", ",", "key", "=", "lambda", "t", ":", "t", "[", "0", "]", ")", ")", "try", ":", "with", "open"...
Write the VMware networking file.
[ "Write", "the", "VMware", "networking", "file", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/vmnet.py#L64-L87
train
GNS3/gns3-server
gns3server/utils/vmnet.py
parse_vmnet_range
def parse_vmnet_range(start, end): """ Parse the vmnet range on the command line. """ class Range(argparse.Action): def __call__(self, parser, args, values, option_string=None): if len(values) != 2: raise argparse.ArgumentTypeError("vmnet range must consist of 2 num...
python
def parse_vmnet_range(start, end): """ Parse the vmnet range on the command line. """ class Range(argparse.Action): def __call__(self, parser, args, values, option_string=None): if len(values) != 2: raise argparse.ArgumentTypeError("vmnet range must consist of 2 num...
[ "def", "parse_vmnet_range", "(", "start", ",", "end", ")", ":", "class", "Range", "(", "argparse", ".", "Action", ")", ":", "def", "__call__", "(", "self", ",", "parser", ",", "args", ",", "values", ",", "option_string", "=", "None", ")", ":", "if", ...
Parse the vmnet range on the command line.
[ "Parse", "the", "vmnet", "range", "on", "the", "command", "line", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/vmnet.py#L90-L103
train
GNS3/gns3-server
gns3server/utils/vmnet.py
vmnet_unix
def vmnet_unix(args, vmnet_range_start, vmnet_range_end): """ Implementation on Linux and Mac OS X. """ if not os.path.exists(VMWARE_NETWORKING_FILE): raise SystemExit("VMware Player, Workstation or Fusion is not installed") if not os.access(VMWARE_NETWORKING_FILE, os.W_OK): raise S...
python
def vmnet_unix(args, vmnet_range_start, vmnet_range_end): """ Implementation on Linux and Mac OS X. """ if not os.path.exists(VMWARE_NETWORKING_FILE): raise SystemExit("VMware Player, Workstation or Fusion is not installed") if not os.access(VMWARE_NETWORKING_FILE, os.W_OK): raise S...
[ "def", "vmnet_unix", "(", "args", ",", "vmnet_range_start", ",", "vmnet_range_end", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "VMWARE_NETWORKING_FILE", ")", ":", "raise", "SystemExit", "(", "\"VMware Player, Workstation or Fusion is not installed\"...
Implementation on Linux and Mac OS X.
[ "Implementation", "on", "Linux", "and", "Mac", "OS", "X", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/vmnet.py#L183-L229
train
GNS3/gns3-server
gns3server/utils/vmnet.py
main
def main(): """ Entry point for the VMNET tool. """ parser = argparse.ArgumentParser(description='%(prog)s add/remove vmnet interfaces') parser.add_argument('-r', "--range", nargs='+', action=parse_vmnet_range(1, 255), type=int, help="vmnet range to add (default is {} {})".f...
python
def main(): """ Entry point for the VMNET tool. """ parser = argparse.ArgumentParser(description='%(prog)s add/remove vmnet interfaces') parser.add_argument('-r', "--range", nargs='+', action=parse_vmnet_range(1, 255), type=int, help="vmnet range to add (default is {} {})".f...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'%(prog)s add/remove vmnet interfaces'", ")", "parser", ".", "add_argument", "(", "'-r'", ",", "\"--range\"", ",", "nargs", "=", "'+'", ",", "action", "="...
Entry point for the VMNET tool.
[ "Entry", "point", "for", "the", "VMNET", "tool", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/vmnet.py#L232-L256
train
GNS3/gns3-server
gns3server/utils/asyncio/telnet_server.py
AsyncioTelnetServer._get_reader
def _get_reader(self, network_reader): """ Get a reader or None if another reader is already reading. """ with (yield from self._lock): if self._reader_process is None: self._reader_process = network_reader if self._reader: if self....
python
def _get_reader(self, network_reader): """ Get a reader or None if another reader is already reading. """ with (yield from self._lock): if self._reader_process is None: self._reader_process = network_reader if self._reader: if self....
[ "def", "_get_reader", "(", "self", ",", "network_reader", ")", ":", "with", "(", "yield", "from", "self", ".", "_lock", ")", ":", "if", "self", ".", "_reader_process", "is", "None", ":", "self", ".", "_reader_process", "=", "network_reader", "if", "self", ...
Get a reader or None if another reader is already reading.
[ "Get", "a", "reader", "or", "None", "if", "another", "reader", "is", "already", "reading", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/telnet_server.py#L223-L234
train
GNS3/gns3-server
gns3server/utils/asyncio/telnet_server.py
AsyncioTelnetServer._read
def _read(self, cmd, buffer, location, reader): """ Reads next op from the buffer or reader""" try: op = buffer[location] cmd.append(op) return op except IndexError: op = yield from reader.read(1) buffer.extend(op) cmd.appen...
python
def _read(self, cmd, buffer, location, reader): """ Reads next op from the buffer or reader""" try: op = buffer[location] cmd.append(op) return op except IndexError: op = yield from reader.read(1) buffer.extend(op) cmd.appen...
[ "def", "_read", "(", "self", ",", "cmd", ",", "buffer", ",", "location", ",", "reader", ")", ":", "try", ":", "op", "=", "buffer", "[", "location", "]", "cmd", ".", "append", "(", "op", ")", "return", "op", "except", "IndexError", ":", "op", "=", ...
Reads next op from the buffer or reader
[ "Reads", "next", "op", "from", "the", "buffer", "or", "reader" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/telnet_server.py#L295-L305
train
GNS3/gns3-server
gns3server/utils/asyncio/telnet_server.py
AsyncioTelnetServer._negotiate
def _negotiate(self, data, connection): """ Performs negotiation commands""" command, payload = data[0], data[1:] if command == NAWS: if len(payload) == 4: columns, rows = struct.unpack(str('!HH'), bytes(payload)) connection.window_size_changed(column...
python
def _negotiate(self, data, connection): """ Performs negotiation commands""" command, payload = data[0], data[1:] if command == NAWS: if len(payload) == 4: columns, rows = struct.unpack(str('!HH'), bytes(payload)) connection.window_size_changed(column...
[ "def", "_negotiate", "(", "self", ",", "data", ",", "connection", ")", ":", "command", ",", "payload", "=", "data", "[", "0", "]", ",", "data", "[", "1", ":", "]", "if", "command", "==", "NAWS", ":", "if", "len", "(", "payload", ")", "==", "4", ...
Performs negotiation commands
[ "Performs", "negotiation", "commands" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/telnet_server.py#L307-L318
train
GNS3/gns3-server
gns3server/utils/ping_stats.py
PingStats.get
def get(cls): """ Get ping statistics :returns: hash """ stats = {} cur_time = time.time() # minimum interval for getting CPU and memory statistics if cur_time < cls._last_measurement or \ cur_time > cls._last_measurement + 1.9: cls...
python
def get(cls): """ Get ping statistics :returns: hash """ stats = {} cur_time = time.time() # minimum interval for getting CPU and memory statistics if cur_time < cls._last_measurement or \ cur_time > cls._last_measurement + 1.9: cls...
[ "def", "get", "(", "cls", ")", ":", "stats", "=", "{", "}", "cur_time", "=", "time", ".", "time", "(", ")", "# minimum interval for getting CPU and memory statistics", "if", "cur_time", "<", "cls", ".", "_last_measurement", "or", "cur_time", ">", "cls", ".", ...
Get ping statistics :returns: hash
[ "Get", "ping", "statistics" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/ping_stats.py#L33-L50
train
GNS3/gns3-server
gns3server/ubridge/ubridge_hypervisor.py
UBridgeHypervisor.send
def send(self, command): """ Sends commands to this hypervisor. :param command: a uBridge hypervisor command :returns: results as a list """ # uBridge responses are of the form: # 1xx yyyyyy\r\n # 1xx yyyyyy\r\n # ... # 100-yyyy\...
python
def send(self, command): """ Sends commands to this hypervisor. :param command: a uBridge hypervisor command :returns: results as a list """ # uBridge responses are of the form: # 1xx yyyyyy\r\n # 1xx yyyyyy\r\n # ... # 100-yyyy\...
[ "def", "send", "(", "self", ",", "command", ")", ":", "# uBridge responses are of the form:", "# 1xx yyyyyy\\r\\n", "# 1xx yyyyyy\\r\\n", "# ...", "# 100-yyyy\\r\\n", "# or", "# 2xx-yyyy\\r\\n", "#", "# Where 1xx is a code from 100-199 for a success or 200-299 for an error"...
Sends commands to this hypervisor. :param command: a uBridge hypervisor command :returns: results as a list
[ "Sends", "commands", "to", "this", "hypervisor", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/ubridge/ubridge_hypervisor.py#L180-L277
train
GNS3/gns3-server
gns3server/web/route.py
parse_request
def parse_request(request, input_schema, raw): """Parse body of request and raise HTTP errors in case of problems""" request.json = {} if not raw: body = yield from request.read() if body: try: request.json = json.loads(body.decode('utf-8')) except Va...
python
def parse_request(request, input_schema, raw): """Parse body of request and raise HTTP errors in case of problems""" request.json = {} if not raw: body = yield from request.read() if body: try: request.json = json.loads(body.decode('utf-8')) except Va...
[ "def", "parse_request", "(", "request", ",", "input_schema", ",", "raw", ")", ":", "request", ".", "json", "=", "{", "}", "if", "not", "raw", ":", "body", "=", "yield", "from", "request", ".", "read", "(", ")", "if", "body", ":", "try", ":", "reque...
Parse body of request and raise HTTP errors in case of problems
[ "Parse", "body", "of", "request", "and", "raise", "HTTP", "errors", "in", "case", "of", "problems" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/route.py#L40-L67
train
GNS3/gns3-server
gns3server/web/route.py
Route.authenticate
def authenticate(cls, request, route, server_config): """ Ask user for authentication :returns: Response if you need to auth the user otherwise None """ if not server_config.getboolean("auth", False): return user = server_config.get("user", "").strip() ...
python
def authenticate(cls, request, route, server_config): """ Ask user for authentication :returns: Response if you need to auth the user otherwise None """ if not server_config.getboolean("auth", False): return user = server_config.get("user", "").strip() ...
[ "def", "authenticate", "(", "cls", ",", "request", ",", "route", ",", "server_config", ")", ":", "if", "not", "server_config", ".", "getboolean", "(", "\"auth\"", ",", "False", ")", ":", "return", "user", "=", "server_config", ".", "get", "(", "\"user\"", ...
Ask user for authentication :returns: Response if you need to auth the user otherwise None
[ "Ask", "user", "for", "authentication" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/route.py#L100-L127
train
GNS3/gns3-server
gns3server/notification_queue.py
NotificationQueue.get
def get(self, timeout): """ When timeout is expire we send a ping notification with server information """ # At first get we return a ping so the client immediately receives data if self._first: self._first = False return ("ping", PingStats.get(), {}) ...
python
def get(self, timeout): """ When timeout is expire we send a ping notification with server information """ # At first get we return a ping so the client immediately receives data if self._first: self._first = False return ("ping", PingStats.get(), {}) ...
[ "def", "get", "(", "self", ",", "timeout", ")", ":", "# At first get we return a ping so the client immediately receives data", "if", "self", ".", "_first", ":", "self", ".", "_first", "=", "False", "return", "(", "\"ping\"", ",", "PingStats", ".", "get", "(", "...
When timeout is expire we send a ping notification with server information
[ "When", "timeout", "is", "expire", "we", "send", "a", "ping", "notification", "with", "server", "information" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/notification_queue.py#L34-L48
train
GNS3/gns3-server
gns3server/notification_queue.py
NotificationQueue.get_json
def get_json(self, timeout): """ Get a message as a JSON """ (action, msg, kwargs) = yield from self.get(timeout) if hasattr(msg, "__json__"): msg = {"action": action, "event": msg.__json__()} else: msg = {"action": action, "event": msg} ms...
python
def get_json(self, timeout): """ Get a message as a JSON """ (action, msg, kwargs) = yield from self.get(timeout) if hasattr(msg, "__json__"): msg = {"action": action, "event": msg.__json__()} else: msg = {"action": action, "event": msg} ms...
[ "def", "get_json", "(", "self", ",", "timeout", ")", ":", "(", "action", ",", "msg", ",", "kwargs", ")", "=", "yield", "from", "self", ".", "get", "(", "timeout", ")", "if", "hasattr", "(", "msg", ",", "\"__json__\"", ")", ":", "msg", "=", "{", "...
Get a message as a JSON
[ "Get", "a", "message", "as", "a", "JSON" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/notification_queue.py#L51-L61
train
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM.close
def close(self): """ Closes this VPCS VM. """ if not (yield from super().close()): return False nio = self._ethernet_adapter.get_nio(0) if isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) if s...
python
def close(self): """ Closes this VPCS VM. """ if not (yield from super().close()): return False nio = self._ethernet_adapter.get_nio(0) if isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) if s...
[ "def", "close", "(", "self", ")", ":", "if", "not", "(", "yield", "from", "super", "(", ")", ".", "close", "(", ")", ")", ":", "return", "False", "nio", "=", "self", ".", "_ethernet_adapter", ".", "get_nio", "(", "0", ")", "if", "isinstance", "(", ...
Closes this VPCS VM.
[ "Closes", "this", "VPCS", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L81-L103
train
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM._check_requirements
def _check_requirements(self): """ Check if VPCS is available with the correct version. """ path = self._vpcs_path() if not path: raise VPCSError("No path to a VPCS executable has been set") # This raise an error if ubridge is not available self.ubri...
python
def _check_requirements(self): """ Check if VPCS is available with the correct version. """ path = self._vpcs_path() if not path: raise VPCSError("No path to a VPCS executable has been set") # This raise an error if ubridge is not available self.ubri...
[ "def", "_check_requirements", "(", "self", ")", ":", "path", "=", "self", ".", "_vpcs_path", "(", ")", "if", "not", "path", ":", "raise", "VPCSError", "(", "\"No path to a VPCS executable has been set\"", ")", "# This raise an error if ubridge is not available", "self",...
Check if VPCS is available with the correct version.
[ "Check", "if", "VPCS", "is", "available", "with", "the", "correct", "version", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L106-L124
train