repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
insomnia-lab/libreant | users/__init__.py | init_db | def init_db(dbURL, pwd_salt_size=None, pwd_rounds=None):
'''Initialize users database
initialize database and create necessary tables
to handle users oprations.
:param dbURL: database url, as described in :func:`init_proxy`
'''
if not dbURL:
dbURL = 'sqlite:///:memory:'
logging.get... | python | def init_db(dbURL, pwd_salt_size=None, pwd_rounds=None):
'''Initialize users database
initialize database and create necessary tables
to handle users oprations.
:param dbURL: database url, as described in :func:`init_proxy`
'''
if not dbURL:
dbURL = 'sqlite:///:memory:'
logging.get... | [
"def",
"init_db",
"(",
"dbURL",
",",
"pwd_salt_size",
"=",
"None",
",",
"pwd_rounds",
"=",
"None",
")",
":",
"if",
"not",
"dbURL",
":",
"dbURL",
"=",
"'sqlite:///:memory:'",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"debug",
"(",
"\"Initializ... | Initialize users database
initialize database and create necessary tables
to handle users oprations.
:param dbURL: database url, as described in :func:`init_proxy` | [
"Initialize",
"users",
"database"
] | 55d529435baf4c05a86b8341899e9f5e14e50245 | https://github.com/insomnia-lab/libreant/blob/55d529435baf4c05a86b8341899e9f5e14e50245/users/__init__.py#L110-L131 | train | 64,600 |
collective/robotsuite | src/robotsuite/__init__.py | normalize | def normalize(s, replace_spaces=True):
"""Normalize non-ascii characters to their closest ascii counterparts
"""
whitelist = (' -' + string.ascii_letters + string.digits)
if type(s) == six.binary_type:
s = six.text_type(s, 'utf-8', 'ignore')
table = {}
for ch in [ch for ch in s if ch n... | python | def normalize(s, replace_spaces=True):
"""Normalize non-ascii characters to their closest ascii counterparts
"""
whitelist = (' -' + string.ascii_letters + string.digits)
if type(s) == six.binary_type:
s = six.text_type(s, 'utf-8', 'ignore')
table = {}
for ch in [ch for ch in s if ch n... | [
"def",
"normalize",
"(",
"s",
",",
"replace_spaces",
"=",
"True",
")",
":",
"whitelist",
"=",
"(",
"' -'",
"+",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
"if",
"type",
"(",
"s",
")",
"==",
"six",
".",
"binary_type",
":",
"s",... | Normalize non-ascii characters to their closest ascii counterparts | [
"Normalize",
"non",
"-",
"ascii",
"characters",
"to",
"their",
"closest",
"ascii",
"counterparts"
] | 58cdd13e12043ba51ab6073a568eddaa668bc49d | https://github.com/collective/robotsuite/blob/58cdd13e12043ba51ab6073a568eddaa668bc49d/src/robotsuite/__init__.py#L54-L77 | train | 64,601 |
collective/robotsuite | src/robotsuite/__init__.py | get_robot_variables | def get_robot_variables():
"""Return list of Robot Framework -compatible cli-variables parsed
from ROBOT_-prefixed environment variable
"""
prefix = 'ROBOT_'
variables = []
def safe_str(s):
if isinstance(s, six.text_type):
return s
else:
return six.text_... | python | def get_robot_variables():
"""Return list of Robot Framework -compatible cli-variables parsed
from ROBOT_-prefixed environment variable
"""
prefix = 'ROBOT_'
variables = []
def safe_str(s):
if isinstance(s, six.text_type):
return s
else:
return six.text_... | [
"def",
"get_robot_variables",
"(",
")",
":",
"prefix",
"=",
"'ROBOT_'",
"variables",
"=",
"[",
"]",
"def",
"safe_str",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"text_type",
")",
":",
"return",
"s",
"else",
":",
"return",
"si... | Return list of Robot Framework -compatible cli-variables parsed
from ROBOT_-prefixed environment variable | [
"Return",
"list",
"of",
"Robot",
"Framework",
"-",
"compatible",
"cli",
"-",
"variables",
"parsed",
"from",
"ROBOT_",
"-",
"prefixed",
"environment",
"variable"
] | 58cdd13e12043ba51ab6073a568eddaa668bc49d | https://github.com/collective/robotsuite/blob/58cdd13e12043ba51ab6073a568eddaa668bc49d/src/robotsuite/__init__.py#L80-L98 | train | 64,602 |
stevemarple/python-MCP342x | MCP342x/__init__.py | MCP342x.convert | def convert(self):
"""Initiate one-shot conversion.
The current settings are used, with the exception of continuous mode."""
c = self.config
c &= (~MCP342x._continuous_mode_mask & 0x7f) # Force one-shot
c |= MCP342x._not_ready_mask # Convert
logger.debu... | python | def convert(self):
"""Initiate one-shot conversion.
The current settings are used, with the exception of continuous mode."""
c = self.config
c &= (~MCP342x._continuous_mode_mask & 0x7f) # Force one-shot
c |= MCP342x._not_ready_mask # Convert
logger.debu... | [
"def",
"convert",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"config",
"c",
"&=",
"(",
"~",
"MCP342x",
".",
"_continuous_mode_mask",
"&",
"0x7f",
")",
"# Force one-shot",
"c",
"|=",
"MCP342x",
".",
"_not_ready_mask",
"# Convert",
"logger",
".",
"debug",... | Initiate one-shot conversion.
The current settings are used, with the exception of continuous mode. | [
"Initiate",
"one",
"-",
"shot",
"conversion",
"."
] | d532e1079c221fc29098d229ddba460cc0ce22a7 | https://github.com/stevemarple/python-MCP342x/blob/d532e1079c221fc29098d229ddba460cc0ce22a7/MCP342x/__init__.py#L296-L304 | train | 64,603 |
chaoss/grimoirelab-manuscripts | manuscripts/esquery.py | ElasticQuery.__get_query_range | def __get_query_range(cls, date_field, start=None, end=None):
"""
Create a filter dict with date_field from start to end dates.
:param date_field: field with the date value
:param start: date with the from value. Should be a datetime.datetime object
of the form: da... | python | def __get_query_range(cls, date_field, start=None, end=None):
"""
Create a filter dict with date_field from start to end dates.
:param date_field: field with the date value
:param start: date with the from value. Should be a datetime.datetime object
of the form: da... | [
"def",
"__get_query_range",
"(",
"cls",
",",
"date_field",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"not",
"start",
"and",
"not",
"end",
":",
"return",
"''",
"start_end",
"=",
"{",
"}",
"if",
"start",
":",
"start_end",
"[",... | Create a filter dict with date_field from start to end dates.
:param date_field: field with the date value
:param start: date with the from value. Should be a datetime.datetime object
of the form: datetime.datetime(2018, 5, 25, 15, 17, 39)
:param end: date with the to valu... | [
"Create",
"a",
"filter",
"dict",
"with",
"date_field",
"from",
"start",
"to",
"end",
"dates",
"."
] | 94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9 | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/esquery.py#L71-L93 | train | 64,604 |
chaoss/grimoirelab-manuscripts | manuscripts/esquery.py | ElasticQuery.__get_query_basic | def __get_query_basic(cls, date_field=None, start=None, end=None,
filters={}):
"""
Create a es_dsl query object with the date range and filters.
:param date_field: field with the date value
:param start: date with the from value, should be a datetime.datetime o... | python | def __get_query_basic(cls, date_field=None, start=None, end=None,
filters={}):
"""
Create a es_dsl query object with the date range and filters.
:param date_field: field with the date value
:param start: date with the from value, should be a datetime.datetime o... | [
"def",
"__get_query_basic",
"(",
"cls",
",",
"date_field",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"filters",
"=",
"{",
"}",
")",
":",
"query_basic",
"=",
"Search",
"(",
")",
"query_filters",
"=",
"cls",
".",
"__get_query_... | Create a es_dsl query object with the date range and filters.
:param date_field: field with the date value
:param start: date with the from value, should be a datetime.datetime object
:param end: date with the to value, should be a datetime.datetime object
:param filters: dict with the ... | [
"Create",
"a",
"es_dsl",
"query",
"object",
"with",
"the",
"date",
"range",
"and",
"filters",
"."
] | 94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9 | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/esquery.py#L96-L133 | train | 64,605 |
chaoss/grimoirelab-manuscripts | manuscripts/esquery.py | ElasticQuery.__get_query_agg_terms | def __get_query_agg_terms(cls, field, agg_id=None):
"""
Create a es_dsl aggregation object based on a term.
:param field: field to be used to aggregate
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"terms": {
... | python | def __get_query_agg_terms(cls, field, agg_id=None):
"""
Create a es_dsl aggregation object based on a term.
:param field: field to be used to aggregate
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"terms": {
... | [
"def",
"__get_query_agg_terms",
"(",
"cls",
",",
"field",
",",
"agg_id",
"=",
"None",
")",
":",
"if",
"not",
"agg_id",
":",
"agg_id",
"=",
"cls",
".",
"AGGREGATION_ID",
"query_agg",
"=",
"A",
"(",
"\"terms\"",
",",
"field",
"=",
"field",
",",
"size",
"... | Create a es_dsl aggregation object based on a term.
:param field: field to be used to aggregate
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"terms": {
"field": <field>,
"size:": <size>,... | [
"Create",
"a",
"es_dsl",
"aggregation",
"object",
"based",
"on",
"a",
"term",
"."
] | 94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9 | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/esquery.py#L136-L156 | train | 64,606 |
chaoss/grimoirelab-manuscripts | manuscripts/esquery.py | ElasticQuery.__get_query_agg_max | def __get_query_agg_max(cls, field, agg_id=None):
"""
Create an es_dsl aggregation object for getting the max value of a field.
:param field: field from which the get the max value
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
... | python | def __get_query_agg_max(cls, field, agg_id=None):
"""
Create an es_dsl aggregation object for getting the max value of a field.
:param field: field from which the get the max value
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
... | [
"def",
"__get_query_agg_max",
"(",
"cls",
",",
"field",
",",
"agg_id",
"=",
"None",
")",
":",
"if",
"not",
"agg_id",
":",
"agg_id",
"=",
"cls",
".",
"AGGREGATION_ID",
"query_agg",
"=",
"A",
"(",
"\"max\"",
",",
"field",
"=",
"field",
")",
"return",
"("... | Create an es_dsl aggregation object for getting the max value of a field.
:param field: field from which the get the max value
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"max": {
"field": <field>
... | [
"Create",
"an",
"es_dsl",
"aggregation",
"object",
"for",
"getting",
"the",
"max",
"value",
"of",
"a",
"field",
"."
] | 94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9 | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/esquery.py#L159-L173 | train | 64,607 |
chaoss/grimoirelab-manuscripts | manuscripts/esquery.py | ElasticQuery.__get_query_agg_avg | def __get_query_agg_avg(cls, field, agg_id=None):
"""
Create an es_dsl aggregation object for getting the average value of a field.
:param field: field from which the get the average value
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
... | python | def __get_query_agg_avg(cls, field, agg_id=None):
"""
Create an es_dsl aggregation object for getting the average value of a field.
:param field: field from which the get the average value
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
... | [
"def",
"__get_query_agg_avg",
"(",
"cls",
",",
"field",
",",
"agg_id",
"=",
"None",
")",
":",
"if",
"not",
"agg_id",
":",
"agg_id",
"=",
"cls",
".",
"AGGREGATION_ID",
"query_agg",
"=",
"A",
"(",
"\"avg\"",
",",
"field",
"=",
"field",
")",
"return",
"("... | Create an es_dsl aggregation object for getting the average value of a field.
:param field: field from which the get the average value
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"avg": {
"field": <field>
... | [
"Create",
"an",
"es_dsl",
"aggregation",
"object",
"for",
"getting",
"the",
"average",
"value",
"of",
"a",
"field",
"."
] | 94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9 | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/esquery.py#L194-L208 | train | 64,608 |
chaoss/grimoirelab-manuscripts | manuscripts/esquery.py | ElasticQuery.__get_query_agg_cardinality | def __get_query_agg_cardinality(cls, field, agg_id=None):
"""
Create an es_dsl aggregation object for getting the approximate count of distinct values of a field.
:param field: field from which the get count of distinct values
:return: a tuple with the aggregation id and es_dsl aggregat... | python | def __get_query_agg_cardinality(cls, field, agg_id=None):
"""
Create an es_dsl aggregation object for getting the approximate count of distinct values of a field.
:param field: field from which the get count of distinct values
:return: a tuple with the aggregation id and es_dsl aggregat... | [
"def",
"__get_query_agg_cardinality",
"(",
"cls",
",",
"field",
",",
"agg_id",
"=",
"None",
")",
":",
"if",
"not",
"agg_id",
":",
"agg_id",
"=",
"cls",
".",
"AGGREGATION_ID",
"query_agg",
"=",
"A",
"(",
"\"cardinality\"",
",",
"field",
"=",
"field",
",",
... | Create an es_dsl aggregation object for getting the approximate count of distinct values of a field.
:param field: field from which the get count of distinct values
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"cardinality": {
... | [
"Create",
"an",
"es_dsl",
"aggregation",
"object",
"for",
"getting",
"the",
"approximate",
"count",
"of",
"distinct",
"values",
"of",
"a",
"field",
"."
] | 94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9 | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/esquery.py#L211-L226 | train | 64,609 |
chaoss/grimoirelab-manuscripts | manuscripts/esquery.py | ElasticQuery.__get_bounds | def __get_bounds(cls, start=None, end=None):
"""
Return a dict with the bounds for a date_histogram agg.
:param start: date from for the date_histogram agg, should be a datetime.datetime object
:param end: date to for the date_histogram agg, should be a datetime.datetime object
... | python | def __get_bounds(cls, start=None, end=None):
"""
Return a dict with the bounds for a date_histogram agg.
:param start: date from for the date_histogram agg, should be a datetime.datetime object
:param end: date to for the date_histogram agg, should be a datetime.datetime object
... | [
"def",
"__get_bounds",
"(",
"cls",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"bounds",
"=",
"{",
"}",
"if",
"start",
"or",
"end",
":",
"# Extend bounds so we have data until start and end",
"start_ts",
"=",
"None",
"end_ts",
"=",
"None",
... | Return a dict with the bounds for a date_histogram agg.
:param start: date from for the date_histogram agg, should be a datetime.datetime object
:param end: date to for the date_histogram agg, should be a datetime.datetime object
:return: a dict with the DSL bounds for a date_histogram aggregat... | [
"Return",
"a",
"dict",
"with",
"the",
"bounds",
"for",
"a",
"date_histogram",
"agg",
"."
] | 94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9 | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/esquery.py#L229-L260 | train | 64,610 |
chaoss/grimoirelab-manuscripts | manuscripts/esquery.py | ElasticQuery.__get_query_agg_ts | def __get_query_agg_ts(cls, field, time_field, interval=None,
time_zone=None, start=None, end=None,
agg_type='count', offset=None):
"""
Create an es_dsl aggregation object for getting the time series values for a field.
:param field: field t... | python | def __get_query_agg_ts(cls, field, time_field, interval=None,
time_zone=None, start=None, end=None,
agg_type='count', offset=None):
"""
Create an es_dsl aggregation object for getting the time series values for a field.
:param field: field t... | [
"def",
"__get_query_agg_ts",
"(",
"cls",
",",
"field",
",",
"time_field",
",",
"interval",
"=",
"None",
",",
"time_zone",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"agg_type",
"=",
"'count'",
",",
"offset",
"=",
"None",
")",... | Create an es_dsl aggregation object for getting the time series values for a field.
:param field: field to get the time series values
:param time_field: field with the date
:param interval: interval to be used to generate the time series values, such as:(year(y),
quarte... | [
"Create",
"an",
"es_dsl",
"aggregation",
"object",
"for",
"getting",
"the",
"time",
"series",
"values",
"for",
"a",
"field",
"."
] | 94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9 | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/esquery.py#L263-L314 | train | 64,611 |
chaoss/grimoirelab-manuscripts | manuscripts/esquery.py | ElasticQuery.get_count | def get_count(cls, date_field=None, start=None, end=None, filters={}):
"""
Build the DSL query for counting the number of items.
:param date_field: field with the date
:param start: date from which to start counting, should be a datetime.datetime object
:param end: date until wh... | python | def get_count(cls, date_field=None, start=None, end=None, filters={}):
"""
Build the DSL query for counting the number of items.
:param date_field: field with the date
:param start: date from which to start counting, should be a datetime.datetime object
:param end: date until wh... | [
"def",
"get_count",
"(",
"cls",
",",
"date_field",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"filters",
"=",
"{",
"}",
")",
":",
"\"\"\" Total number of items \"\"\"",
"query_basic",
"=",
"cls",
".",
"__get_query_basic",
"(",
"d... | Build the DSL query for counting the number of items.
:param date_field: field with the date
:param start: date from which to start counting, should be a datetime.datetime object
:param end: date until which to count items, should be a datetime.datetime object
:param filters: dict with ... | [
"Build",
"the",
"DSL",
"query",
"for",
"counting",
"the",
"number",
"of",
"items",
"."
] | 94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9 | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/esquery.py#L317-L333 | train | 64,612 |
pricingassistant/mongokat | mongokat/document.py | Document.ensure_fields | def ensure_fields(self, fields, force_refetch=False):
""" Makes sure we fetched the fields, and populate them if not. """
# We fetched with fields=None, we should have fetched them all
if self._fetched_fields is None or self._initialized_with_doc:
return
if force_refetch:
... | python | def ensure_fields(self, fields, force_refetch=False):
""" Makes sure we fetched the fields, and populate them if not. """
# We fetched with fields=None, we should have fetched them all
if self._fetched_fields is None or self._initialized_with_doc:
return
if force_refetch:
... | [
"def",
"ensure_fields",
"(",
"self",
",",
"fields",
",",
"force_refetch",
"=",
"False",
")",
":",
"# We fetched with fields=None, we should have fetched them all",
"if",
"self",
".",
"_fetched_fields",
"is",
"None",
"or",
"self",
".",
"_initialized_with_doc",
":",
"re... | Makes sure we fetched the fields, and populate them if not. | [
"Makes",
"sure",
"we",
"fetched",
"the",
"fields",
"and",
"populate",
"them",
"if",
"not",
"."
] | 61eaf4bc1c4cc359c6f9592ec97b9a04d9561411 | https://github.com/pricingassistant/mongokat/blob/61eaf4bc1c4cc359c6f9592ec97b9a04d9561411/mongokat/document.py#L82-L100 | train | 64,613 |
pricingassistant/mongokat | mongokat/document.py | Document.refetch_fields | def refetch_fields(self, missing_fields):
""" Refetches a list of fields from the DB """
db_fields = self.mongokat_collection.find_one({"_id": self["_id"]}, fields={k: 1 for k in missing_fields})
self._fetched_fields += tuple(missing_fields)
if not db_fields:
return
... | python | def refetch_fields(self, missing_fields):
""" Refetches a list of fields from the DB """
db_fields = self.mongokat_collection.find_one({"_id": self["_id"]}, fields={k: 1 for k in missing_fields})
self._fetched_fields += tuple(missing_fields)
if not db_fields:
return
... | [
"def",
"refetch_fields",
"(",
"self",
",",
"missing_fields",
")",
":",
"db_fields",
"=",
"self",
".",
"mongokat_collection",
".",
"find_one",
"(",
"{",
"\"_id\"",
":",
"self",
"[",
"\"_id\"",
"]",
"}",
",",
"fields",
"=",
"{",
"k",
":",
"1",
"for",
"k"... | Refetches a list of fields from the DB | [
"Refetches",
"a",
"list",
"of",
"fields",
"from",
"the",
"DB"
] | 61eaf4bc1c4cc359c6f9592ec97b9a04d9561411 | https://github.com/pricingassistant/mongokat/blob/61eaf4bc1c4cc359c6f9592ec97b9a04d9561411/mongokat/document.py#L102-L112 | train | 64,614 |
pricingassistant/mongokat | mongokat/document.py | Document.unset_fields | def unset_fields(self, fields):
""" Removes this list of fields from both the local object and the DB. """
self.mongokat_collection.update_one({"_id": self["_id"]}, {"$unset": {
f: 1 for f in fields
}})
for f in fields:
if f in self:
del self[f] | python | def unset_fields(self, fields):
""" Removes this list of fields from both the local object and the DB. """
self.mongokat_collection.update_one({"_id": self["_id"]}, {"$unset": {
f: 1 for f in fields
}})
for f in fields:
if f in self:
del self[f] | [
"def",
"unset_fields",
"(",
"self",
",",
"fields",
")",
":",
"self",
".",
"mongokat_collection",
".",
"update_one",
"(",
"{",
"\"_id\"",
":",
"self",
"[",
"\"_id\"",
"]",
"}",
",",
"{",
"\"$unset\"",
":",
"{",
"f",
":",
"1",
"for",
"f",
"in",
"fields... | Removes this list of fields from both the local object and the DB. | [
"Removes",
"this",
"list",
"of",
"fields",
"from",
"both",
"the",
"local",
"object",
"and",
"the",
"DB",
"."
] | 61eaf4bc1c4cc359c6f9592ec97b9a04d9561411 | https://github.com/pricingassistant/mongokat/blob/61eaf4bc1c4cc359c6f9592ec97b9a04d9561411/mongokat/document.py#L114-L123 | train | 64,615 |
pricingassistant/mongokat | mongokat/document.py | Document.save_partial | def save_partial(self, data=None, allow_protected_fields=False, **kwargs):
""" Saves just the currently set fields in the database. """
# Backwards compat, deprecated argument
if "dotnotation" in kwargs:
del kwargs["dotnotation"]
if data is None:
data = dotdict... | python | def save_partial(self, data=None, allow_protected_fields=False, **kwargs):
""" Saves just the currently set fields in the database. """
# Backwards compat, deprecated argument
if "dotnotation" in kwargs:
del kwargs["dotnotation"]
if data is None:
data = dotdict... | [
"def",
"save_partial",
"(",
"self",
",",
"data",
"=",
"None",
",",
"allow_protected_fields",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Backwards compat, deprecated argument",
"if",
"\"dotnotation\"",
"in",
"kwargs",
":",
"del",
"kwargs",
"[",
"\"dotnot... | Saves just the currently set fields in the database. | [
"Saves",
"just",
"the",
"currently",
"set",
"fields",
"in",
"the",
"database",
"."
] | 61eaf4bc1c4cc359c6f9592ec97b9a04d9561411 | https://github.com/pricingassistant/mongokat/blob/61eaf4bc1c4cc359c6f9592ec97b9a04d9561411/mongokat/document.py#L170-L199 | train | 64,616 |
nccgroup/opinel | opinel/utils/cli_parser.py | read_default_args | def read_default_args(tool_name):
"""
Read default argument values for a given tool
:param tool_name: Name of the script to read the default arguments for
:return: Dictionary of default arguments (shared + tool-specific)
"""
global opinel_arg_dir
... | python | def read_default_args(tool_name):
"""
Read default argument values for a given tool
:param tool_name: Name of the script to read the default arguments for
:return: Dictionary of default arguments (shared + tool-specific)
"""
global opinel_arg_dir
... | [
"def",
"read_default_args",
"(",
"tool_name",
")",
":",
"global",
"opinel_arg_dir",
"profile_name",
"=",
"'default'",
"# h4ck to have an early read of the profile name",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"sys",
".",
"argv",
")",
":",
"if",
"arg",
"==... | Read default argument values for a given tool
:param tool_name: Name of the script to read the default arguments for
:return: Dictionary of default arguments (shared + tool-specific) | [
"Read",
"default",
"argument",
"values",
"for",
"a",
"given",
"tool"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/cli_parser.py#L143-L179 | train | 64,617 |
nccgroup/opinel | opinel/utils/console.py | prompt | def prompt(test_input = None):
"""
Prompt function that works for Python2 and Python3
:param test_input: Value to be returned when testing
:return: Value typed by user (or passed in argument when testing)
"""
if test_input != None:
if type(te... | python | def prompt(test_input = None):
"""
Prompt function that works for Python2 and Python3
:param test_input: Value to be returned when testing
:return: Value typed by user (or passed in argument when testing)
"""
if test_input != None:
if type(te... | [
"def",
"prompt",
"(",
"test_input",
"=",
"None",
")",
":",
"if",
"test_input",
"!=",
"None",
":",
"if",
"type",
"(",
"test_input",
")",
"==",
"list",
"and",
"len",
"(",
"test_input",
")",
":",
"choice",
"=",
"test_input",
".",
"pop",
"(",
"0",
")",
... | Prompt function that works for Python2 and Python3
:param test_input: Value to be returned when testing
:return: Value typed by user (or passed in argument when testing) | [
"Prompt",
"function",
"that",
"works",
"for",
"Python2",
"and",
"Python3"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/console.py#L73-L94 | train | 64,618 |
nccgroup/opinel | opinel/utils/console.py | prompt_4_mfa_code | def prompt_4_mfa_code(activate = False, input = None):
"""
Prompt for an MFA code
:param activate: Set to true when prompting for the 2nd code when activating a new MFA device
:param input: Used for unit testing
:return: The MFA c... | python | def prompt_4_mfa_code(activate = False, input = None):
"""
Prompt for an MFA code
:param activate: Set to true when prompting for the 2nd code when activating a new MFA device
:param input: Used for unit testing
:return: The MFA c... | [
"def",
"prompt_4_mfa_code",
"(",
"activate",
"=",
"False",
",",
"input",
"=",
"None",
")",
":",
"while",
"True",
":",
"if",
"activate",
":",
"prompt_string",
"=",
"'Enter the next value: '",
"else",
":",
"prompt_string",
"=",
"'Enter your MFA code (or \\'q\\' to abo... | Prompt for an MFA code
:param activate: Set to true when prompting for the 2nd code when activating a new MFA device
:param input: Used for unit testing
:return: The MFA code | [
"Prompt",
"for",
"an",
"MFA",
"code"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/console.py#L97-L120 | train | 64,619 |
nccgroup/opinel | opinel/utils/console.py | prompt_4_mfa_serial | def prompt_4_mfa_serial(input = None):
"""
Prompt for an MFA serial number
:param input: Used for unit testing
:return: The MFA serial number
"""
return prompt_4_value('Enter your MFA serial:', required = False, regex = re_mfa_serial_format, reg... | python | def prompt_4_mfa_serial(input = None):
"""
Prompt for an MFA serial number
:param input: Used for unit testing
:return: The MFA serial number
"""
return prompt_4_value('Enter your MFA serial:', required = False, regex = re_mfa_serial_format, reg... | [
"def",
"prompt_4_mfa_serial",
"(",
"input",
"=",
"None",
")",
":",
"return",
"prompt_4_value",
"(",
"'Enter your MFA serial:'",
",",
"required",
"=",
"False",
",",
"regex",
"=",
"re_mfa_serial_format",
",",
"regex_format",
"=",
"mfa_serial_format",
",",
"input",
"... | Prompt for an MFA serial number
:param input: Used for unit testing
:return: The MFA serial number | [
"Prompt",
"for",
"an",
"MFA",
"serial",
"number"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/console.py#L123-L131 | train | 64,620 |
nccgroup/opinel | opinel/utils/console.py | prompt_4_overwrite | def prompt_4_overwrite(filename, force_write, input = None):
"""
Prompt whether the file should be overwritten
:param filename: Name of the file about to be written
:param force_write: Skip confirmation prompt if this flag is set
:param input: ... | python | def prompt_4_overwrite(filename, force_write, input = None):
"""
Prompt whether the file should be overwritten
:param filename: Name of the file about to be written
:param force_write: Skip confirmation prompt if this flag is set
:param input: ... | [
"def",
"prompt_4_overwrite",
"(",
"filename",
",",
"force_write",
",",
"input",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
"or",
"force_write",
":",
"return",
"True",
"return",
"prompt_4_yes_no",
"(",
"'File... | Prompt whether the file should be overwritten
:param filename: Name of the file about to be written
:param force_write: Skip confirmation prompt if this flag is set
:param input: Used for unit testing
:return: Boolean ... | [
"Prompt",
"whether",
"the",
"file",
"should",
"be",
"overwritten"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/console.py#L134-L146 | train | 64,621 |
sveetch/django-feedparser | django_feedparser/utils.py | get_feed_renderer | def get_feed_renderer(engines, name):
"""
From engine name, load the engine path and return the renderer class
Raise 'FeedparserError' if any loading error
"""
if name not in engines:
raise FeedparserError("Given feed name '{}' does not exists in 'settings.FEED_RENDER_ENGINES'".format(n... | python | def get_feed_renderer(engines, name):
"""
From engine name, load the engine path and return the renderer class
Raise 'FeedparserError' if any loading error
"""
if name not in engines:
raise FeedparserError("Given feed name '{}' does not exists in 'settings.FEED_RENDER_ENGINES'".format(n... | [
"def",
"get_feed_renderer",
"(",
"engines",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"engines",
":",
"raise",
"FeedparserError",
"(",
"\"Given feed name '{}' does not exists in 'settings.FEED_RENDER_ENGINES'\"",
".",
"format",
"(",
"name",
")",
")",
"renderer... | From engine name, load the engine path and return the renderer class
Raise 'FeedparserError' if any loading error | [
"From",
"engine",
"name",
"load",
"the",
"engine",
"path",
"and",
"return",
"the",
"renderer",
"class",
"Raise",
"FeedparserError",
"if",
"any",
"loading",
"error"
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/utils.py#L37-L48 | train | 64,622 |
mixmastamyk/console | console/utils.py | clear_line | def clear_line(mode=2):
''' Clear the current line.
Arguments:
mode: | 0 | 'forward' | 'right' - Clear cursor to end of line.
| 1 | 'backward' | 'left' - Clear cursor to beginning of line.
| 2 | 'full' - Clear entire line.
Note:
... | python | def clear_line(mode=2):
''' Clear the current line.
Arguments:
mode: | 0 | 'forward' | 'right' - Clear cursor to end of line.
| 1 | 'backward' | 'left' - Clear cursor to beginning of line.
| 2 | 'full' - Clear entire line.
Note:
... | [
"def",
"clear_line",
"(",
"mode",
"=",
"2",
")",
":",
"text",
"=",
"sc",
".",
"erase_line",
"(",
"_mode_map",
".",
"get",
"(",
"mode",
",",
"mode",
")",
")",
"_write",
"(",
"text",
")",
"return",
"text"
] | Clear the current line.
Arguments:
mode: | 0 | 'forward' | 'right' - Clear cursor to end of line.
| 1 | 'backward' | 'left' - Clear cursor to beginning of line.
| 2 | 'full' - Clear entire line.
Note:
Cursor position does ... | [
"Clear",
"the",
"current",
"line",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/utils.py#L55-L69 | train | 64,623 |
mixmastamyk/console | console/utils.py | wait_key | def wait_key(keys=None):
''' Waits for a keypress at the console and returns it.
"Where's the any key?"
Arguments:
keys - if passed, wait for this specific key, e.g. ESC.
may be a tuple.
Returns:
char or ESC - depending on key hit.
None... | python | def wait_key(keys=None):
''' Waits for a keypress at the console and returns it.
"Where's the any key?"
Arguments:
keys - if passed, wait for this specific key, e.g. ESC.
may be a tuple.
Returns:
char or ESC - depending on key hit.
None... | [
"def",
"wait_key",
"(",
"keys",
"=",
"None",
")",
":",
"if",
"is_a_tty",
"(",
")",
":",
"if",
"keys",
":",
"if",
"not",
"isinstance",
"(",
"keys",
",",
"tuple",
")",
":",
"keys",
"=",
"(",
"keys",
",",
")",
"while",
"True",
":",
"key",
"=",
"_g... | Waits for a keypress at the console and returns it.
"Where's the any key?"
Arguments:
keys - if passed, wait for this specific key, e.g. ESC.
may be a tuple.
Returns:
char or ESC - depending on key hit.
None - immediately under i/o redirect... | [
"Waits",
"for",
"a",
"keypress",
"at",
"the",
"console",
"and",
"returns",
"it",
".",
"Where",
"s",
"the",
"any",
"key?"
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/utils.py#L166-L186 | train | 64,624 |
nccgroup/opinel | opinel/utils/aws.py | build_region_list | def build_region_list(service, chosen_regions = [], partition_name = 'aws'):
"""
Build the list of target region names
:param service:
:param chosen_regions:
:param partition_name:
:return:
"""
service = 'ec2containerservice' if service == 'ecs' else service # Of course things aren't t... | python | def build_region_list(service, chosen_regions = [], partition_name = 'aws'):
"""
Build the list of target region names
:param service:
:param chosen_regions:
:param partition_name:
:return:
"""
service = 'ec2containerservice' if service == 'ecs' else service # Of course things aren't t... | [
"def",
"build_region_list",
"(",
"service",
",",
"chosen_regions",
"=",
"[",
"]",
",",
"partition_name",
"=",
"'aws'",
")",
":",
"service",
"=",
"'ec2containerservice'",
"if",
"service",
"==",
"'ecs'",
"else",
"service",
"# Of course things aren't that easy...",
"# ... | Build the list of target region names
:param service:
:param chosen_regions:
:param partition_name:
:return: | [
"Build",
"the",
"list",
"of",
"target",
"region",
"names"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/aws.py#L12-L28 | train | 64,625 |
nccgroup/opinel | opinel/utils/aws.py | connect_service | def connect_service(service, credentials, region_name = None, config = None, silent = False):
"""
Instantiates an AWS API client
:param service:
:param credentials:
:param region_name:
:param config:
:param silent:
:return:
"""
api_client = None
try:
client_params =... | python | def connect_service(service, credentials, region_name = None, config = None, silent = False):
"""
Instantiates an AWS API client
:param service:
:param credentials:
:param region_name:
:param config:
:param silent:
:return:
"""
api_client = None
try:
client_params =... | [
"def",
"connect_service",
"(",
"service",
",",
"credentials",
",",
"region_name",
"=",
"None",
",",
"config",
"=",
"None",
",",
"silent",
"=",
"False",
")",
":",
"api_client",
"=",
"None",
"try",
":",
"client_params",
"=",
"{",
"}",
"client_params",
"[",
... | Instantiates an AWS API client
:param service:
:param credentials:
:param region_name:
:param config:
:param silent:
:return: | [
"Instantiates",
"an",
"AWS",
"API",
"client"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/aws.py#L31-L65 | train | 64,626 |
nccgroup/opinel | opinel/utils/aws.py | handle_truncated_response | def handle_truncated_response(callback, params, entities):
"""
Handle truncated responses
:param callback:
:param params:
:param entities:
:return:
"""
results = {}
for entity in entities:
results[entity] = []
while True:
try:
marker_found = False
... | python | def handle_truncated_response(callback, params, entities):
"""
Handle truncated responses
:param callback:
:param params:
:param entities:
:return:
"""
results = {}
for entity in entities:
results[entity] = []
while True:
try:
marker_found = False
... | [
"def",
"handle_truncated_response",
"(",
"callback",
",",
"params",
",",
"entities",
")",
":",
"results",
"=",
"{",
"}",
"for",
"entity",
"in",
"entities",
":",
"results",
"[",
"entity",
"]",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"marker_found... | Handle truncated responses
:param callback:
:param params:
:param entities:
:return: | [
"Handle",
"truncated",
"responses"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/aws.py#L108-L139 | train | 64,627 |
justanr/Flask-Transfer | examples/JPEGr/JPEGr/transfer.py | pdftojpg | def pdftojpg(filehandle, meta):
"""Converts a PDF to a JPG and places it back onto the FileStorage instance
passed to it as a BytesIO object.
Optional meta arguments are:
* resolution: int or (int, int) used for wand to determine resolution,
defaults to 300.
* width: new width of th... | python | def pdftojpg(filehandle, meta):
"""Converts a PDF to a JPG and places it back onto the FileStorage instance
passed to it as a BytesIO object.
Optional meta arguments are:
* resolution: int or (int, int) used for wand to determine resolution,
defaults to 300.
* width: new width of th... | [
"def",
"pdftojpg",
"(",
"filehandle",
",",
"meta",
")",
":",
"resolution",
"=",
"meta",
".",
"get",
"(",
"'resolution'",
",",
"300",
")",
"width",
"=",
"meta",
".",
"get",
"(",
"'width'",
",",
"1080",
")",
"bgcolor",
"=",
"Color",
"(",
"meta",
".",
... | Converts a PDF to a JPG and places it back onto the FileStorage instance
passed to it as a BytesIO object.
Optional meta arguments are:
* resolution: int or (int, int) used for wand to determine resolution,
defaults to 300.
* width: new width of the image for resizing, defaults to 1080
... | [
"Converts",
"a",
"PDF",
"to",
"a",
"JPG",
"and",
"places",
"it",
"back",
"onto",
"the",
"FileStorage",
"instance",
"passed",
"to",
"it",
"as",
"a",
"BytesIO",
"object",
"."
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/examples/JPEGr/JPEGr/transfer.py#L15-L41 | train | 64,628 |
justanr/Flask-Transfer | examples/JPEGr/JPEGr/transfer.py | change_filename | def change_filename(filehandle, meta):
"""Changes the filename to reflect the conversion from PDF to JPG.
This method will preserve the original filename in the meta dictionary.
"""
filename = secure_filename(meta.get('filename', filehandle.filename))
basename, _ = os.path.splitext(filename)
met... | python | def change_filename(filehandle, meta):
"""Changes the filename to reflect the conversion from PDF to JPG.
This method will preserve the original filename in the meta dictionary.
"""
filename = secure_filename(meta.get('filename', filehandle.filename))
basename, _ = os.path.splitext(filename)
met... | [
"def",
"change_filename",
"(",
"filehandle",
",",
"meta",
")",
":",
"filename",
"=",
"secure_filename",
"(",
"meta",
".",
"get",
"(",
"'filename'",
",",
"filehandle",
".",
"filename",
")",
")",
"basename",
",",
"_",
"=",
"os",
".",
"path",
".",
"splitext... | Changes the filename to reflect the conversion from PDF to JPG.
This method will preserve the original filename in the meta dictionary. | [
"Changes",
"the",
"filename",
"to",
"reflect",
"the",
"conversion",
"from",
"PDF",
"to",
"JPG",
".",
"This",
"method",
"will",
"preserve",
"the",
"original",
"filename",
"in",
"the",
"meta",
"dictionary",
"."
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/examples/JPEGr/JPEGr/transfer.py#L45-L53 | train | 64,629 |
justanr/Flask-Transfer | examples/JPEGr/JPEGr/transfer.py | pdf_saver | def pdf_saver(filehandle, *args, **kwargs):
"Uses werkzeug.FileStorage instance to save the converted image."
fullpath = get_save_path(filehandle.filename)
filehandle.save(fullpath, buffer_size=kwargs.get('buffer_size', 16384)) | python | def pdf_saver(filehandle, *args, **kwargs):
"Uses werkzeug.FileStorage instance to save the converted image."
fullpath = get_save_path(filehandle.filename)
filehandle.save(fullpath, buffer_size=kwargs.get('buffer_size', 16384)) | [
"def",
"pdf_saver",
"(",
"filehandle",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fullpath",
"=",
"get_save_path",
"(",
"filehandle",
".",
"filename",
")",
"filehandle",
".",
"save",
"(",
"fullpath",
",",
"buffer_size",
"=",
"kwargs",
".",
"ge... | Uses werkzeug.FileStorage instance to save the converted image. | [
"Uses",
"werkzeug",
".",
"FileStorage",
"instance",
"to",
"save",
"the",
"converted",
"image",
"."
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/examples/JPEGr/JPEGr/transfer.py#L80-L83 | train | 64,630 |
nccgroup/opinel | opinel/utils/fs.py | load_data | def load_data(data_file, key_name = None, local_file = False, format = 'json'):
"""
Load a JSON data file
:param data_file:
:param key_name:
:param local_file:
:return:
"""
if local_file:
if data_file.startswith('/'):
src_file = data_file
else:
sr... | python | def load_data(data_file, key_name = None, local_file = False, format = 'json'):
"""
Load a JSON data file
:param data_file:
:param key_name:
:param local_file:
:return:
"""
if local_file:
if data_file.startswith('/'):
src_file = data_file
else:
sr... | [
"def",
"load_data",
"(",
"data_file",
",",
"key_name",
"=",
"None",
",",
"local_file",
"=",
"False",
",",
"format",
"=",
"'json'",
")",
":",
"if",
"local_file",
":",
"if",
"data_file",
".",
"startswith",
"(",
"'/'",
")",
":",
"src_file",
"=",
"data_file"... | Load a JSON data file
:param data_file:
:param key_name:
:param local_file:
:return: | [
"Load",
"a",
"JSON",
"data",
"file"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/fs.py#L25-L57 | train | 64,631 |
nccgroup/opinel | opinel/utils/fs.py | read_ip_ranges | def read_ip_ranges(filename, local_file = True, ip_only = False, conditions = []):
"""
Returns the list of IP prefixes from an ip-ranges file
:param filename:
:param local_file:
:param conditions:
:param ip_only:
:return:
"""
targets = []
data = load_data(filename, local_file = ... | python | def read_ip_ranges(filename, local_file = True, ip_only = False, conditions = []):
"""
Returns the list of IP prefixes from an ip-ranges file
:param filename:
:param local_file:
:param conditions:
:param ip_only:
:return:
"""
targets = []
data = load_data(filename, local_file = ... | [
"def",
"read_ip_ranges",
"(",
"filename",
",",
"local_file",
"=",
"True",
",",
"ip_only",
"=",
"False",
",",
"conditions",
"=",
"[",
"]",
")",
":",
"targets",
"=",
"[",
"]",
"data",
"=",
"load_data",
"(",
"filename",
",",
"local_file",
"=",
"local_file",... | Returns the list of IP prefixes from an ip-ranges file
:param filename:
:param local_file:
:param conditions:
:param ip_only:
:return: | [
"Returns",
"the",
"list",
"of",
"IP",
"prefixes",
"from",
"an",
"ip",
"-",
"ranges",
"file"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/fs.py#L60-L96 | train | 64,632 |
dag/flask-zodb | flask_zodb.py | ZODB.init_app | def init_app(self, app):
"""Configure a Flask application to use this ZODB extension."""
assert 'zodb' not in app.extensions, \
'app already initiated for zodb'
app.extensions['zodb'] = _ZODBState(self, app)
app.teardown_request(self.close_db) | python | def init_app(self, app):
"""Configure a Flask application to use this ZODB extension."""
assert 'zodb' not in app.extensions, \
'app already initiated for zodb'
app.extensions['zodb'] = _ZODBState(self, app)
app.teardown_request(self.close_db) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"assert",
"'zodb'",
"not",
"in",
"app",
".",
"extensions",
",",
"'app already initiated for zodb'",
"app",
".",
"extensions",
"[",
"'zodb'",
"]",
"=",
"_ZODBState",
"(",
"self",
",",
"app",
")",
"app",
... | Configure a Flask application to use this ZODB extension. | [
"Configure",
"a",
"Flask",
"application",
"to",
"use",
"this",
"ZODB",
"extension",
"."
] | c5451aba28cd5b303c71654b7ef2b62edb08afe8 | https://github.com/dag/flask-zodb/blob/c5451aba28cd5b303c71654b7ef2b62edb08afe8/flask_zodb.py#L41-L46 | train | 64,633 |
dag/flask-zodb | flask_zodb.py | ZODB.close_db | def close_db(self, exception):
"""Added as a `~flask.Flask.teardown_request` to applications to
commit the transaction and disconnect ZODB if it was used during
the request."""
if self.is_connected:
if exception is None and not transaction.isDoomed():
transact... | python | def close_db(self, exception):
"""Added as a `~flask.Flask.teardown_request` to applications to
commit the transaction and disconnect ZODB if it was used during
the request."""
if self.is_connected:
if exception is None and not transaction.isDoomed():
transact... | [
"def",
"close_db",
"(",
"self",
",",
"exception",
")",
":",
"if",
"self",
".",
"is_connected",
":",
"if",
"exception",
"is",
"None",
"and",
"not",
"transaction",
".",
"isDoomed",
"(",
")",
":",
"transaction",
".",
"commit",
"(",
")",
"else",
":",
"tran... | Added as a `~flask.Flask.teardown_request` to applications to
commit the transaction and disconnect ZODB if it was used during
the request. | [
"Added",
"as",
"a",
"~flask",
".",
"Flask",
".",
"teardown_request",
"to",
"applications",
"to",
"commit",
"the",
"transaction",
"and",
"disconnect",
"ZODB",
"if",
"it",
"was",
"used",
"during",
"the",
"request",
"."
] | c5451aba28cd5b303c71654b7ef2b62edb08afe8 | https://github.com/dag/flask-zodb/blob/c5451aba28cd5b303c71654b7ef2b62edb08afe8/flask_zodb.py#L48-L57 | train | 64,634 |
dag/flask-zodb | flask_zodb.py | ZODB.connection | def connection(self):
"""Request-bound database connection."""
assert flask.has_request_context(), \
'tried to connect zodb outside request'
if not self.is_connected:
connector = flask.current_app.extensions['zodb']
flask._request_ctx_stack.top.zodb_connect... | python | def connection(self):
"""Request-bound database connection."""
assert flask.has_request_context(), \
'tried to connect zodb outside request'
if not self.is_connected:
connector = flask.current_app.extensions['zodb']
flask._request_ctx_stack.top.zodb_connect... | [
"def",
"connection",
"(",
"self",
")",
":",
"assert",
"flask",
".",
"has_request_context",
"(",
")",
",",
"'tried to connect zodb outside request'",
"if",
"not",
"self",
".",
"is_connected",
":",
"connector",
"=",
"flask",
".",
"current_app",
".",
"extensions",
... | Request-bound database connection. | [
"Request",
"-",
"bound",
"database",
"connection",
"."
] | c5451aba28cd5b303c71654b7ef2b62edb08afe8 | https://github.com/dag/flask-zodb/blob/c5451aba28cd5b303c71654b7ef2b62edb08afe8/flask_zodb.py#L79-L87 | train | 64,635 |
nccgroup/opinel | opinel/services/iam.py | add_user_to_group | def add_user_to_group(iam_client, user, group, quiet = False):
"""
Add an IAM user to an IAM group
:param iam_client:
:param group:
:param user:
:param user_info:
:param dry_run:
:return:
"""
if not quiet:
printInfo('Adding user to group %s...' % group)
iam_client.ad... | python | def add_user_to_group(iam_client, user, group, quiet = False):
"""
Add an IAM user to an IAM group
:param iam_client:
:param group:
:param user:
:param user_info:
:param dry_run:
:return:
"""
if not quiet:
printInfo('Adding user to group %s...' % group)
iam_client.ad... | [
"def",
"add_user_to_group",
"(",
"iam_client",
",",
"user",
",",
"group",
",",
"quiet",
"=",
"False",
")",
":",
"if",
"not",
"quiet",
":",
"printInfo",
"(",
"'Adding user to group %s...'",
"%",
"group",
")",
"iam_client",
".",
"add_user_to_group",
"(",
"GroupN... | Add an IAM user to an IAM group
:param iam_client:
:param group:
:param user:
:param user_info:
:param dry_run:
:return: | [
"Add",
"an",
"IAM",
"user",
"to",
"an",
"IAM",
"group"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/services/iam.py#L11-L24 | train | 64,636 |
nccgroup/opinel | opinel/services/iam.py | delete_virtual_mfa_device | def delete_virtual_mfa_device(iam_client, mfa_serial):
"""
Delete a vritual MFA device given its serial number
:param iam_client:
:param mfa_serial:
:return:
"""
try:
printInfo('Deleting MFA device %s...' % mfa_serial)
iam_client.delete_virtual_mfa_device(SerialNumber = mfa_... | python | def delete_virtual_mfa_device(iam_client, mfa_serial):
"""
Delete a vritual MFA device given its serial number
:param iam_client:
:param mfa_serial:
:return:
"""
try:
printInfo('Deleting MFA device %s...' % mfa_serial)
iam_client.delete_virtual_mfa_device(SerialNumber = mfa_... | [
"def",
"delete_virtual_mfa_device",
"(",
"iam_client",
",",
"mfa_serial",
")",
":",
"try",
":",
"printInfo",
"(",
"'Deleting MFA device %s...'",
"%",
"mfa_serial",
")",
"iam_client",
".",
"delete_virtual_mfa_device",
"(",
"SerialNumber",
"=",
"mfa_serial",
")",
"excep... | Delete a vritual MFA device given its serial number
:param iam_client:
:param mfa_serial:
:return: | [
"Delete",
"a",
"vritual",
"MFA",
"device",
"given",
"its",
"serial",
"number"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/services/iam.py#L230-L244 | train | 64,637 |
nccgroup/opinel | opinel/services/iam.py | init_group_category_regex | def init_group_category_regex(category_groups, category_regex_args):
"""
Initialize and compile regular expression for category groups
:param category_regex_args: List of string regex
:return: List of compiled regex
"""
category_regex = []
authorized_empt... | python | def init_group_category_regex(category_groups, category_regex_args):
"""
Initialize and compile regular expression for category groups
:param category_regex_args: List of string regex
:return: List of compiled regex
"""
category_regex = []
authorized_empt... | [
"def",
"init_group_category_regex",
"(",
"category_groups",
",",
"category_regex_args",
")",
":",
"category_regex",
"=",
"[",
"]",
"authorized_empty_regex",
"=",
"1",
"if",
"len",
"(",
"category_regex_args",
")",
"and",
"len",
"(",
"category_groups",
")",
"!=",
"l... | Initialize and compile regular expression for category groups
:param category_regex_args: List of string regex
:return: List of compiled regex | [
"Initialize",
"and",
"compile",
"regular",
"expression",
"for",
"category",
"groups"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/services/iam.py#L257-L280 | train | 64,638 |
mixmastamyk/console | console/core.py | _HighColorPaletteBuilder._get_extended_palette_entry | def _get_extended_palette_entry(self, name, index, is_hex=False):
''' Compute extended entry, once on the fly. '''
values = None
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'extended' in self._palette_support: # build entry
if is_hex:
index = str(find_near... | python | def _get_extended_palette_entry(self, name, index, is_hex=False):
''' Compute extended entry, once on the fly. '''
values = None
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'extended' in self._palette_support: # build entry
if is_hex:
index = str(find_near... | [
"def",
"_get_extended_palette_entry",
"(",
"self",
",",
"name",
",",
"index",
",",
"is_hex",
"=",
"False",
")",
":",
"values",
"=",
"None",
"is_fbterm",
"=",
"(",
"env",
".",
"TERM",
"==",
"'fbterm'",
")",
"# sigh",
"if",
"'extended'",
"in",
"self",
".",... | Compute extended entry, once on the fly. | [
"Compute",
"extended",
"entry",
"once",
"on",
"the",
"fly",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L180-L208 | train | 64,639 |
mixmastamyk/console | console/core.py | _HighColorPaletteBuilder._get_true_palette_entry | def _get_true_palette_entry(self, name, digits):
''' Compute truecolor entry, once on the fly.
values must become sequence of decimal int strings: ('1', '2', '3')
'''
values = None
type_digits = type(digits)
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'tru... | python | def _get_true_palette_entry(self, name, digits):
''' Compute truecolor entry, once on the fly.
values must become sequence of decimal int strings: ('1', '2', '3')
'''
values = None
type_digits = type(digits)
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'tru... | [
"def",
"_get_true_palette_entry",
"(",
"self",
",",
"name",
",",
"digits",
")",
":",
"values",
"=",
"None",
"type_digits",
"=",
"type",
"(",
"digits",
")",
"is_fbterm",
"=",
"(",
"env",
".",
"TERM",
"==",
"'fbterm'",
")",
"# sigh",
"if",
"'truecolor'",
"... | Compute truecolor entry, once on the fly.
values must become sequence of decimal int strings: ('1', '2', '3') | [
"Compute",
"truecolor",
"entry",
"once",
"on",
"the",
"fly",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L210-L259 | train | 64,640 |
mixmastamyk/console | console/core.py | _HighColorPaletteBuilder._index_to_ansi_values | def _index_to_ansi_values(self, index):
''' Converts an palette index to the corresponding ANSI color.
Arguments:
index - an int (from 0-15)
Returns:
index as str in a list for compatibility with values.
'''
if self.__class__.__name__[0]... | python | def _index_to_ansi_values(self, index):
''' Converts an palette index to the corresponding ANSI color.
Arguments:
index - an int (from 0-15)
Returns:
index as str in a list for compatibility with values.
'''
if self.__class__.__name__[0]... | [
"def",
"_index_to_ansi_values",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"__class__",
".",
"__name__",
"[",
"0",
"]",
"==",
"'F'",
":",
"# Foreground",
"if",
"index",
"<",
"8",
":",
"index",
"+=",
"ANSI_FG_LO_BASE",
"else",
":",
"index",
... | Converts an palette index to the corresponding ANSI color.
Arguments:
index - an int (from 0-15)
Returns:
index as str in a list for compatibility with values. | [
"Converts",
"an",
"palette",
"index",
"to",
"the",
"corresponding",
"ANSI",
"color",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L287-L305 | train | 64,641 |
mixmastamyk/console | console/core.py | _HighColorPaletteBuilder._create_entry | def _create_entry(self, name, values, fbterm=False):
''' Render first values as string and place as first code,
save, and return attr.
'''
if fbterm:
attr = _PaletteEntryFBTerm(self, name.upper(), ';'.join(values))
else:
attr = _PaletteEntry(self, name... | python | def _create_entry(self, name, values, fbterm=False):
''' Render first values as string and place as first code,
save, and return attr.
'''
if fbterm:
attr = _PaletteEntryFBTerm(self, name.upper(), ';'.join(values))
else:
attr = _PaletteEntry(self, name... | [
"def",
"_create_entry",
"(",
"self",
",",
"name",
",",
"values",
",",
"fbterm",
"=",
"False",
")",
":",
"if",
"fbterm",
":",
"attr",
"=",
"_PaletteEntryFBTerm",
"(",
"self",
",",
"name",
".",
"upper",
"(",
")",
",",
"';'",
".",
"join",
"(",
"values",... | Render first values as string and place as first code,
save, and return attr. | [
"Render",
"first",
"values",
"as",
"string",
"and",
"place",
"as",
"first",
"code",
"save",
"and",
"return",
"attr",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L307-L316 | train | 64,642 |
mixmastamyk/console | console/core.py | _LineWriter.write | def write(self, data):
''' This could be a bit less clumsy. '''
if data == '\n': # print does this
return self.stream.write(data)
else:
bytes_ = 0
for line in data.splitlines(True):
nl = ''
if line.endswith('\n'): # mv nl to e... | python | def write(self, data):
''' This could be a bit less clumsy. '''
if data == '\n': # print does this
return self.stream.write(data)
else:
bytes_ = 0
for line in data.splitlines(True):
nl = ''
if line.endswith('\n'): # mv nl to e... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"==",
"'\\n'",
":",
"# print does this",
"return",
"self",
".",
"stream",
".",
"write",
"(",
"data",
")",
"else",
":",
"bytes_",
"=",
"0",
"for",
"line",
"in",
"data",
".",
"splitlines... | This could be a bit less clumsy. | [
"This",
"could",
"be",
"a",
"bit",
"less",
"clumsy",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L334-L348 | train | 64,643 |
mixmastamyk/console | console/core.py | _PaletteEntry.set_output | def set_output(self, outfile):
''' Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last.
'''
if self._orig_stdout: # restore Usted
sys.stdout = self._orig_stdout
self._stream = ... | python | def set_output(self, outfile):
''' Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last.
'''
if self._orig_stdout: # restore Usted
sys.stdout = self._orig_stdout
self._stream = ... | [
"def",
"set_output",
"(",
"self",
",",
"outfile",
")",
":",
"if",
"self",
".",
"_orig_stdout",
":",
"# restore Usted",
"sys",
".",
"stdout",
"=",
"self",
".",
"_orig_stdout",
"self",
".",
"_stream",
"=",
"outfile",
"sys",
".",
"stdout",
"=",
"_LineWriter",... | Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last. | [
"Set",
"s",
"the",
"output",
"file",
"currently",
"only",
"useful",
"with",
"context",
"-",
"managers",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/core.py#L468-L478 | train | 64,644 |
mixmastamyk/console | console/progress.py | ProgressBar._render | def _render(self):
''' Standard rendering of bar graph. '''
cm_chars = self._comp_style(self.icons[_ic] * self._num_complete_chars)
em_chars = self._empt_style(self.icons[_ie] * self._num_empty_chars)
return f'{self._first}{cm_chars}{em_chars}{self._last} {self._lbl}' | python | def _render(self):
''' Standard rendering of bar graph. '''
cm_chars = self._comp_style(self.icons[_ic] * self._num_complete_chars)
em_chars = self._empt_style(self.icons[_ie] * self._num_empty_chars)
return f'{self._first}{cm_chars}{em_chars}{self._last} {self._lbl}' | [
"def",
"_render",
"(",
"self",
")",
":",
"cm_chars",
"=",
"self",
".",
"_comp_style",
"(",
"self",
".",
"icons",
"[",
"_ic",
"]",
"*",
"self",
".",
"_num_complete_chars",
")",
"em_chars",
"=",
"self",
".",
"_empt_style",
"(",
"self",
".",
"icons",
"[",... | Standard rendering of bar graph. | [
"Standard",
"rendering",
"of",
"bar",
"graph",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/progress.py#L298-L302 | train | 64,645 |
mixmastamyk/console | console/progress.py | ProgressBar._render_internal_label | def _render_internal_label(self):
''' Render with a label inside the bar graph. '''
ncc = self._num_complete_chars
bar = self._lbl.center(self.iwidth)
cm_chars = self._comp_style(bar[:ncc])
em_chars = self._empt_style(bar[ncc:])
return f'{self._first}{cm_chars}{em_chars}{... | python | def _render_internal_label(self):
''' Render with a label inside the bar graph. '''
ncc = self._num_complete_chars
bar = self._lbl.center(self.iwidth)
cm_chars = self._comp_style(bar[:ncc])
em_chars = self._empt_style(bar[ncc:])
return f'{self._first}{cm_chars}{em_chars}{... | [
"def",
"_render_internal_label",
"(",
"self",
")",
":",
"ncc",
"=",
"self",
".",
"_num_complete_chars",
"bar",
"=",
"self",
".",
"_lbl",
".",
"center",
"(",
"self",
".",
"iwidth",
")",
"cm_chars",
"=",
"self",
".",
"_comp_style",
"(",
"bar",
"[",
":",
... | Render with a label inside the bar graph. | [
"Render",
"with",
"a",
"label",
"inside",
"the",
"bar",
"graph",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/progress.py#L304-L310 | train | 64,646 |
mixmastamyk/console | console/progress.py | HiDefProgressBar._get_ncc | def _get_ncc(self, width, ratio):
''' Get the number of complete chars.
This one figures the remainder for the partial char as well.
'''
sub_chars = round(width * ratio * self.partial_chars_len)
ncc, self.remainder = divmod(sub_chars, self.partial_chars_len)
return n... | python | def _get_ncc(self, width, ratio):
''' Get the number of complete chars.
This one figures the remainder for the partial char as well.
'''
sub_chars = round(width * ratio * self.partial_chars_len)
ncc, self.remainder = divmod(sub_chars, self.partial_chars_len)
return n... | [
"def",
"_get_ncc",
"(",
"self",
",",
"width",
",",
"ratio",
")",
":",
"sub_chars",
"=",
"round",
"(",
"width",
"*",
"ratio",
"*",
"self",
".",
"partial_chars_len",
")",
"ncc",
",",
"self",
".",
"remainder",
"=",
"divmod",
"(",
"sub_chars",
",",
"self",... | Get the number of complete chars.
This one figures the remainder for the partial char as well. | [
"Get",
"the",
"number",
"of",
"complete",
"chars",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/progress.py#L335-L342 | train | 64,647 |
mixmastamyk/console | console/progress.py | HiDefProgressBar._render | def _render(self):
''' figure partial character '''
p_char = ''
if not self.done and self.remainder:
p_style = self._comp_style
if self.partial_char_extra_style:
if p_style is str:
p_style = self.partial_char_extra_style
... | python | def _render(self):
''' figure partial character '''
p_char = ''
if not self.done and self.remainder:
p_style = self._comp_style
if self.partial_char_extra_style:
if p_style is str:
p_style = self.partial_char_extra_style
... | [
"def",
"_render",
"(",
"self",
")",
":",
"p_char",
"=",
"''",
"if",
"not",
"self",
".",
"done",
"and",
"self",
".",
"remainder",
":",
"p_style",
"=",
"self",
".",
"_comp_style",
"if",
"self",
".",
"partial_char_extra_style",
":",
"if",
"p_style",
"is",
... | figure partial character | [
"figure",
"partial",
"character"
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/progress.py#L344-L360 | train | 64,648 |
nccgroup/opinel | opinel/utils/threads.py | thread_work | def thread_work(targets, function, params = {}, num_threads = 0):
"""
Generic multithreading helper
:param targets:
:param function:
:param params:
:param num_threads:
:return:
"""
q = Queue(maxsize=0)
if not num_threads:
num_threads = len(targets)
for i in range(nu... | python | def thread_work(targets, function, params = {}, num_threads = 0):
"""
Generic multithreading helper
:param targets:
:param function:
:param params:
:param num_threads:
:return:
"""
q = Queue(maxsize=0)
if not num_threads:
num_threads = len(targets)
for i in range(nu... | [
"def",
"thread_work",
"(",
"targets",
",",
"function",
",",
"params",
"=",
"{",
"}",
",",
"num_threads",
"=",
"0",
")",
":",
"q",
"=",
"Queue",
"(",
"maxsize",
"=",
"0",
")",
"if",
"not",
"num_threads",
":",
"num_threads",
"=",
"len",
"(",
"targets",... | Generic multithreading helper
:param targets:
:param function:
:param params:
:param num_threads:
:return: | [
"Generic",
"multithreading",
"helper"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/threads.py#L15-L35 | train | 64,649 |
nccgroup/opinel | opinel/utils/threads.py | threaded_per_region | def threaded_per_region(q, params):
"""
Helper for multithreading on a per-region basis
:param q:
:param params:
:return:
"""
while True:
try:
params['region'] = q.get()
method = params['method']
method(params)
except Exception as e:
... | python | def threaded_per_region(q, params):
"""
Helper for multithreading on a per-region basis
:param q:
:param params:
:return:
"""
while True:
try:
params['region'] = q.get()
method = params['method']
method(params)
except Exception as e:
... | [
"def",
"threaded_per_region",
"(",
"q",
",",
"params",
")",
":",
"while",
"True",
":",
"try",
":",
"params",
"[",
"'region'",
"]",
"=",
"q",
".",
"get",
"(",
")",
"method",
"=",
"params",
"[",
"'method'",
"]",
"method",
"(",
"params",
")",
"except",
... | Helper for multithreading on a per-region basis
:param q:
:param params:
:return: | [
"Helper",
"for",
"multithreading",
"on",
"a",
"per",
"-",
"region",
"basis"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/threads.py#L38-L55 | train | 64,650 |
mixmastamyk/console | console/screen.py | Screen.location | def location(self, x=None, y=None):
''' Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!')
'''
stream = self._stream
stream.write(self.save_p... | python | def location(self, x=None, y=None):
''' Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!')
'''
stream = self._stream
stream.write(self.save_p... | [
"def",
"location",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"stream",
"=",
"self",
".",
"_stream",
"stream",
".",
"write",
"(",
"self",
".",
"save_pos",
")",
"# cursor position",
"if",
"x",
"is",
"not",
"None",
"and",
"y... | Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!') | [
"Temporarily",
"move",
"the",
"cursor",
"perform",
"work",
"and",
"return",
"to",
"the",
"previous",
"location",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/screen.py#L143-L167 | train | 64,651 |
mixmastamyk/console | console/screen.py | Screen.fullscreen | def fullscreen(self):
''' Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!')
'''
stream = self._stream
stream.write(self.alt_screen_enable)
... | python | def fullscreen(self):
''' Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!')
'''
stream = self._stream
stream.write(self.alt_screen_enable)
... | [
"def",
"fullscreen",
"(",
"self",
")",
":",
"stream",
"=",
"self",
".",
"_stream",
"stream",
".",
"write",
"(",
"self",
".",
"alt_screen_enable",
")",
"stream",
".",
"write",
"(",
"str",
"(",
"self",
".",
"save_title",
"(",
"0",
")",
")",
")",
"# 0 =... | Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!') | [
"Context",
"Manager",
"that",
"enters",
"full",
"-",
"screen",
"mode",
"and",
"restores",
"normal",
"mode",
"on",
"exit",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/screen.py#L170-L188 | train | 64,652 |
mixmastamyk/console | console/screen.py | Screen.hidden_cursor | def hidden_cursor(self):
''' Context Manager that hides the cursor and restores it on exit.
::
with screen.hidden_cursor():
print('Clandestine activity…')
'''
stream = self._stream
stream.write(self.hide_cursor)
stream.flush()
... | python | def hidden_cursor(self):
''' Context Manager that hides the cursor and restores it on exit.
::
with screen.hidden_cursor():
print('Clandestine activity…')
'''
stream = self._stream
stream.write(self.hide_cursor)
stream.flush()
... | [
"def",
"hidden_cursor",
"(",
"self",
")",
":",
"stream",
"=",
"self",
".",
"_stream",
"stream",
".",
"write",
"(",
"self",
".",
"hide_cursor",
")",
"stream",
".",
"flush",
"(",
")",
"try",
":",
"yield",
"self",
"finally",
":",
"stream",
".",
"write",
... | Context Manager that hides the cursor and restores it on exit.
::
with screen.hidden_cursor():
print('Clandestine activity…') | [
"Context",
"Manager",
"that",
"hides",
"the",
"cursor",
"and",
"restores",
"it",
"on",
"exit",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/screen.py#L191-L206 | train | 64,653 |
mapleoin/undecorated | undecorated.py | undecorated | def undecorated(o):
"""Remove all decorators from a function, method or class"""
# class decorator
if type(o) is type:
return o
try:
# python2
closure = o.func_closure
except AttributeError:
pass
try:
# python3
closure = o.__closure__
except ... | python | def undecorated(o):
"""Remove all decorators from a function, method or class"""
# class decorator
if type(o) is type:
return o
try:
# python2
closure = o.func_closure
except AttributeError:
pass
try:
# python3
closure = o.__closure__
except ... | [
"def",
"undecorated",
"(",
"o",
")",
":",
"# class decorator",
"if",
"type",
"(",
"o",
")",
"is",
"type",
":",
"return",
"o",
"try",
":",
"# python2",
"closure",
"=",
"o",
".",
"func_closure",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"# pytho... | Remove all decorators from a function, method or class | [
"Remove",
"all",
"decorators",
"from",
"a",
"function",
"method",
"or",
"class"
] | 79843ce8e8466dbbd26a3626b148fea7f2b26ab1 | https://github.com/mapleoin/undecorated/blob/79843ce8e8466dbbd26a3626b148fea7f2b26ab1/undecorated.py#L22-L60 | train | 64,654 |
nccgroup/opinel | opinel/utils/credentials.py | assume_role | def assume_role(role_name, credentials, role_arn, role_session_name, silent = False):
"""
Assume role and save credentials
:param role_name:
:param credentials:
:param role_arn:
:param role_session_name:
:param silent:
:return:
"""
external_id = credentials.pop('ExternalId') if ... | python | def assume_role(role_name, credentials, role_arn, role_session_name, silent = False):
"""
Assume role and save credentials
:param role_name:
:param credentials:
:param role_arn:
:param role_session_name:
:param silent:
:return:
"""
external_id = credentials.pop('ExternalId') if ... | [
"def",
"assume_role",
"(",
"role_name",
",",
"credentials",
",",
"role_arn",
",",
"role_session_name",
",",
"silent",
"=",
"False",
")",
":",
"external_id",
"=",
"credentials",
".",
"pop",
"(",
"'ExternalId'",
")",
"if",
"'ExternalId'",
"in",
"credentials",
"e... | Assume role and save credentials
:param role_name:
:param credentials:
:param role_arn:
:param role_session_name:
:param silent:
:return: | [
"Assume",
"role",
"and",
"save",
"credentials"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L57-L93 | train | 64,655 |
nccgroup/opinel | opinel/utils/credentials.py | generate_password | def generate_password(length=16):
"""
Generate a password using random characters from uppercase, lowercase, digits, and symbols
:param length: Length of the password to be generated
:return: The random password
"""
chars = string.ascii_letters + ... | python | def generate_password(length=16):
"""
Generate a password using random characters from uppercase, lowercase, digits, and symbols
:param length: Length of the password to be generated
:return: The random password
"""
chars = string.ascii_letters + ... | [
"def",
"generate_password",
"(",
"length",
"=",
"16",
")",
":",
"chars",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'!@#$%^&*()_+-=[]{};:,<.>?|'",
"modulus",
"=",
"len",
"(",
"chars",
")",
"pchars",
"=",
"os",
".",
"urandom",
... | Generate a password using random characters from uppercase, lowercase, digits, and symbols
:param length: Length of the password to be generated
:return: The random password | [
"Generate",
"a",
"password",
"using",
"random",
"characters",
"from",
"uppercase",
"lowercase",
"digits",
"and",
"symbols"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L129-L142 | train | 64,656 |
nccgroup/opinel | opinel/utils/credentials.py | init_sts_session | def init_sts_session(profile_name, credentials, duration = 28800, session_name = None, save_creds = True):
"""
Fetch STS credentials
:param profile_name:
:param credentials:
:param duration:
:param session_name:
:param save_creds:
:return:
"""
# Set STS arguments
sts_args = ... | python | def init_sts_session(profile_name, credentials, duration = 28800, session_name = None, save_creds = True):
"""
Fetch STS credentials
:param profile_name:
:param credentials:
:param duration:
:param session_name:
:param save_creds:
:return:
"""
# Set STS arguments
sts_args = ... | [
"def",
"init_sts_session",
"(",
"profile_name",
",",
"credentials",
",",
"duration",
"=",
"28800",
",",
"session_name",
"=",
"None",
",",
"save_creds",
"=",
"True",
")",
":",
"# Set STS arguments",
"sts_args",
"=",
"{",
"'DurationSeconds'",
":",
"duration",
"}",... | Fetch STS credentials
:param profile_name:
:param credentials:
:param duration:
:param session_name:
:param save_creds:
:return: | [
"Fetch",
"STS",
"credentials"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L155-L187 | train | 64,657 |
nccgroup/opinel | opinel/utils/credentials.py | read_creds_from_aws_credentials_file | def read_creds_from_aws_credentials_file(profile_name, credentials_file = aws_credentials_file):
"""
Read credentials from AWS config file
:param profile_name:
:param credentials_file:
:return:
"""
credentials = init_creds()
profile_found = False
try:
# Make sure the ~.aws f... | python | def read_creds_from_aws_credentials_file(profile_name, credentials_file = aws_credentials_file):
"""
Read credentials from AWS config file
:param profile_name:
:param credentials_file:
:return:
"""
credentials = init_creds()
profile_found = False
try:
# Make sure the ~.aws f... | [
"def",
"read_creds_from_aws_credentials_file",
"(",
"profile_name",
",",
"credentials_file",
"=",
"aws_credentials_file",
")",
":",
"credentials",
"=",
"init_creds",
"(",
")",
"profile_found",
"=",
"False",
"try",
":",
"# Make sure the ~.aws folder exists",
"if",
"not",
... | Read credentials from AWS config file
:param profile_name:
:param credentials_file:
:return: | [
"Read",
"credentials",
"from",
"AWS",
"config",
"file"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L190-L227 | train | 64,658 |
nccgroup/opinel | opinel/utils/credentials.py | read_creds_from_csv | def read_creds_from_csv(filename):
"""
Read credentials from a CSV file
:param filename:
:return:
"""
key_id = None
secret = None
mfa_serial = None
secret_next = False
with open(filename, 'rt') as csvfile:
for i, line in enumerate(csvfile):
values = line.spli... | python | def read_creds_from_csv(filename):
"""
Read credentials from a CSV file
:param filename:
:return:
"""
key_id = None
secret = None
mfa_serial = None
secret_next = False
with open(filename, 'rt') as csvfile:
for i, line in enumerate(csvfile):
values = line.spli... | [
"def",
"read_creds_from_csv",
"(",
"filename",
")",
":",
"key_id",
"=",
"None",
"secret",
"=",
"None",
"mfa_serial",
"=",
"None",
"secret_next",
"=",
"False",
"with",
"open",
"(",
"filename",
",",
"'rt'",
")",
"as",
"csvfile",
":",
"for",
"i",
",",
"line... | Read credentials from a CSV file
:param filename:
:return: | [
"Read",
"credentials",
"from",
"a",
"CSV",
"file"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L230-L253 | train | 64,659 |
nccgroup/opinel | opinel/utils/credentials.py | read_creds_from_environment_variables | def read_creds_from_environment_variables():
"""
Read credentials from environment variables
:return:
"""
creds = init_creds()
# Check environment variables
if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ:
creds['AccessKeyId'] = os.environ['AWS_ACCESS_... | python | def read_creds_from_environment_variables():
"""
Read credentials from environment variables
:return:
"""
creds = init_creds()
# Check environment variables
if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ:
creds['AccessKeyId'] = os.environ['AWS_ACCESS_... | [
"def",
"read_creds_from_environment_variables",
"(",
")",
":",
"creds",
"=",
"init_creds",
"(",
")",
"# Check environment variables",
"if",
"'AWS_ACCESS_KEY_ID'",
"in",
"os",
".",
"environ",
"and",
"'AWS_SECRET_ACCESS_KEY'",
"in",
"os",
".",
"environ",
":",
"creds",
... | Read credentials from environment variables
:return: | [
"Read",
"credentials",
"from",
"environment",
"variables"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L295-L308 | train | 64,660 |
nccgroup/opinel | opinel/utils/credentials.py | read_profile_from_environment_variables | def read_profile_from_environment_variables():
"""
Read profiles from env
:return:
"""
role_arn = os.environ.get('AWS_ROLE_ARN', None)
external_id = os.environ.get('AWS_EXTERNAL_ID', None)
return role_arn, external_id | python | def read_profile_from_environment_variables():
"""
Read profiles from env
:return:
"""
role_arn = os.environ.get('AWS_ROLE_ARN', None)
external_id = os.environ.get('AWS_EXTERNAL_ID', None)
return role_arn, external_id | [
"def",
"read_profile_from_environment_variables",
"(",
")",
":",
"role_arn",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_ROLE_ARN'",
",",
"None",
")",
"external_id",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_EXTERNAL_ID'",
",",
"None",
")",
"re... | Read profiles from env
:return: | [
"Read",
"profiles",
"from",
"env"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L311-L319 | train | 64,661 |
nccgroup/opinel | opinel/utils/credentials.py | read_profile_from_aws_config_file | def read_profile_from_aws_config_file(profile_name, config_file = aws_config_file):
"""
Read profiles from AWS config file
:param profile_name:
:param config_file:
:return:
"""
role_arn = None
source_profile = 'default'
mfa_serial = None
profile_found = False
external_id = N... | python | def read_profile_from_aws_config_file(profile_name, config_file = aws_config_file):
"""
Read profiles from AWS config file
:param profile_name:
:param config_file:
:return:
"""
role_arn = None
source_profile = 'default'
mfa_serial = None
profile_found = False
external_id = N... | [
"def",
"read_profile_from_aws_config_file",
"(",
"profile_name",
",",
"config_file",
"=",
"aws_config_file",
")",
":",
"role_arn",
"=",
"None",
"source_profile",
"=",
"'default'",
"mfa_serial",
"=",
"None",
"profile_found",
"=",
"False",
"external_id",
"=",
"None",
... | Read profiles from AWS config file
:param profile_name:
:param config_file:
:return: | [
"Read",
"profiles",
"from",
"AWS",
"config",
"file"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L322-L358 | train | 64,662 |
nccgroup/opinel | opinel/utils/credentials.py | write_creds_to_aws_credentials_file | def write_creds_to_aws_credentials_file(profile_name, credentials, credentials_file = aws_credentials_file):
"""
Write credentials to AWS config file
:param profile_name:
:param credentials:
:param credentials_file:
:return:
"""
profile_found = False
profile_ever_found = False
s... | python | def write_creds_to_aws_credentials_file(profile_name, credentials, credentials_file = aws_credentials_file):
"""
Write credentials to AWS config file
:param profile_name:
:param credentials:
:param credentials_file:
:return:
"""
profile_found = False
profile_ever_found = False
s... | [
"def",
"write_creds_to_aws_credentials_file",
"(",
"profile_name",
",",
"credentials",
",",
"credentials_file",
"=",
"aws_credentials_file",
")",
":",
"profile_found",
"=",
"False",
"profile_ever_found",
"=",
"False",
"session_token_written",
"=",
"False",
"security_token_w... | Write credentials to AWS config file
:param profile_name:
:param credentials:
:param credentials_file:
:return: | [
"Write",
"credentials",
"to",
"AWS",
"config",
"file"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L373-L437 | train | 64,663 |
nccgroup/opinel | opinel/utils/credentials.py | complete_profile | def complete_profile(f, credentials, session_token_written, mfa_serial_written):
"""
Append session token and mfa serial if needed
:param f:
:param credentials:
:param session_token_written:
:param mfa_serial_written:
:return:
"""
session_token = credentials['SessionToken'] if 'Sess... | python | def complete_profile(f, credentials, session_token_written, mfa_serial_written):
"""
Append session token and mfa serial if needed
:param f:
:param credentials:
:param session_token_written:
:param mfa_serial_written:
:return:
"""
session_token = credentials['SessionToken'] if 'Sess... | [
"def",
"complete_profile",
"(",
"f",
",",
"credentials",
",",
"session_token_written",
",",
"mfa_serial_written",
")",
":",
"session_token",
"=",
"credentials",
"[",
"'SessionToken'",
"]",
"if",
"'SessionToken'",
"in",
"credentials",
"else",
"None",
"mfa_serial",
"=... | Append session token and mfa serial if needed
:param f:
:param credentials:
:param session_token_written:
:param mfa_serial_written:
:return: | [
"Append",
"session",
"token",
"and",
"mfa",
"serial",
"if",
"needed"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/credentials.py#L440-L455 | train | 64,664 |
nccgroup/opinel | opinel/services/cloudformation.py | get_stackset_ready_accounts | def get_stackset_ready_accounts(credentials, account_ids, quiet=True):
"""
Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_a... | python | def get_stackset_ready_accounts(credentials, account_ids, quiet=True):
"""
Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_a... | [
"def",
"get_stackset_ready_accounts",
"(",
"credentials",
",",
"account_ids",
",",
"quiet",
"=",
"True",
")",
":",
"api_client",
"=",
"connect_service",
"(",
"'sts'",
",",
"credentials",
",",
"silent",
"=",
"True",
")",
"configured_account_ids",
"=",
"[",
"]",
... | Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_account_ids: List of AWS accounts to check for Stackset configuration
... | [
"Verify",
"which",
"AWS",
"accounts",
"have",
"been",
"configured",
"for",
"CloudFormation",
"stack",
"set",
"by",
"attempting",
"to",
"assume",
"the",
"stack",
"set",
"execution",
"role"
] | 2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606 | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/services/cloudformation.py#L154-L176 | train | 64,665 |
sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer.fetch | def fetch(self, url):
"""
Get the feed content using 'requests'
"""
try:
r = requests.get(url, timeout=self.timeout)
except requests.exceptions.Timeout:
if not self.safe:
raise
else:
return None
... | python | def fetch(self, url):
"""
Get the feed content using 'requests'
"""
try:
r = requests.get(url, timeout=self.timeout)
except requests.exceptions.Timeout:
if not self.safe:
raise
else:
return None
... | [
"def",
"fetch",
"(",
"self",
",",
"url",
")",
":",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"if",
"not",
"self",
".",
... | Get the feed content using 'requests' | [
"Get",
"the",
"feed",
"content",
"using",
"requests"
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L39-L55 | train | 64,666 |
sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer.parse | def parse(self, content):
"""
Parse the fetched feed content
Feedparser returned dict contain a 'bozo' key which can be '1' if the feed
is malformed.
Return None if the feed is malformed and 'bozo_accept'
is 'False', else return the feed content dict.
... | python | def parse(self, content):
"""
Parse the fetched feed content
Feedparser returned dict contain a 'bozo' key which can be '1' if the feed
is malformed.
Return None if the feed is malformed and 'bozo_accept'
is 'False', else return the feed content dict.
... | [
"def",
"parse",
"(",
"self",
",",
"content",
")",
":",
"if",
"content",
"is",
"None",
":",
"return",
"None",
"feed",
"=",
"feedparser",
".",
"parse",
"(",
"content",
")",
"# When feed is malformed",
"if",
"feed",
"[",
"'bozo'",
"]",
":",
"# keep track of t... | Parse the fetched feed content
Feedparser returned dict contain a 'bozo' key which can be '1' if the feed
is malformed.
Return None if the feed is malformed and 'bozo_accept'
is 'False', else return the feed content dict.
If the feed is malformed but ... | [
"Parse",
"the",
"fetched",
"feed",
"content",
"Feedparser",
"returned",
"dict",
"contain",
"a",
"bozo",
"key",
"which",
"can",
"be",
"1",
"if",
"the",
"feed",
"is",
"malformed",
".",
"Return",
"None",
"if",
"the",
"feed",
"is",
"malformed",
"and",
"bozo_ac... | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L57-L91 | train | 64,667 |
sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer._hash_url | def _hash_url(self, url):
"""
Hash the URL to an md5sum.
"""
if isinstance(url, six.text_type):
url = url.encode('utf-8')
return hashlib.md5(url).hexdigest() | python | def _hash_url(self, url):
"""
Hash the URL to an md5sum.
"""
if isinstance(url, six.text_type):
url = url.encode('utf-8')
return hashlib.md5(url).hexdigest() | [
"def",
"_hash_url",
"(",
"self",
",",
"url",
")",
":",
"if",
"isinstance",
"(",
"url",
",",
"six",
".",
"text_type",
")",
":",
"url",
"=",
"url",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"hashlib",
".",
"md5",
"(",
"url",
")",
".",
"hexdigest"... | Hash the URL to an md5sum. | [
"Hash",
"the",
"URL",
"to",
"an",
"md5sum",
"."
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L93-L101 | train | 64,668 |
sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer.get | def get(self, url, expiration):
"""
Fetch the feed if no cache exist or if cache is stale
"""
# Hash url to have a shorter key and add it expiration time to avoid clash for
# other url usage with different expiration
cache_key = self.cache_key.format(**{
'id'... | python | def get(self, url, expiration):
"""
Fetch the feed if no cache exist or if cache is stale
"""
# Hash url to have a shorter key and add it expiration time to avoid clash for
# other url usage with different expiration
cache_key = self.cache_key.format(**{
'id'... | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"expiration",
")",
":",
"# Hash url to have a shorter key and add it expiration time to avoid clash for ",
"# other url usage with different expiration",
"cache_key",
"=",
"self",
".",
"cache_key",
".",
"format",
"(",
"*",
"*",
... | Fetch the feed if no cache exist or if cache is stale | [
"Fetch",
"the",
"feed",
"if",
"no",
"cache",
"exist",
"or",
"if",
"cache",
"is",
"stale"
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L103-L122 | train | 64,669 |
sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer.get_context | def get_context(self, url, expiration):
"""
Build template context with formatted feed content
"""
self._feed = self.get(url, expiration)
return {
self.feed_context_name: self.format_feed_content(self._feed),
} | python | def get_context(self, url, expiration):
"""
Build template context with formatted feed content
"""
self._feed = self.get(url, expiration)
return {
self.feed_context_name: self.format_feed_content(self._feed),
} | [
"def",
"get_context",
"(",
"self",
",",
"url",
",",
"expiration",
")",
":",
"self",
".",
"_feed",
"=",
"self",
".",
"get",
"(",
"url",
",",
"expiration",
")",
"return",
"{",
"self",
".",
"feed_context_name",
":",
"self",
".",
"format_feed_content",
"(",
... | Build template context with formatted feed content | [
"Build",
"template",
"context",
"with",
"formatted",
"feed",
"content"
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L133-L141 | train | 64,670 |
sveetch/django-feedparser | django_feedparser/renderer.py | FeedBasicRenderer.render | def render(self, url, template=None, expiration=0):
"""
Render feed template
"""
template = template or self.default_template
return render_to_string(template, self.get_context(url, expiration)) | python | def render(self, url, template=None, expiration=0):
"""
Render feed template
"""
template = template or self.default_template
return render_to_string(template, self.get_context(url, expiration)) | [
"def",
"render",
"(",
"self",
",",
"url",
",",
"template",
"=",
"None",
",",
"expiration",
"=",
"0",
")",
":",
"template",
"=",
"template",
"or",
"self",
".",
"default_template",
"return",
"render_to_string",
"(",
"template",
",",
"self",
".",
"get_context... | Render feed template | [
"Render",
"feed",
"template"
] | 78be6a3ea095a90e4b28cad1b8893ddf1febf60e | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/renderer.py#L143-L149 | train | 64,671 |
mixmastamyk/console | console/windows.py | is_ansi_capable | def is_ansi_capable():
''' Check to see whether this version of Windows is recent enough to
support "ANSI VT"" processing.
'''
BUILD_ANSI_AVAIL = 10586 # Win10 TH2
CURRENT_VERS = sys.getwindowsversion()[:3]
if CURRENT_VERS[2] > BUILD_ANSI_AVAIL:
result = True
else:
resu... | python | def is_ansi_capable():
''' Check to see whether this version of Windows is recent enough to
support "ANSI VT"" processing.
'''
BUILD_ANSI_AVAIL = 10586 # Win10 TH2
CURRENT_VERS = sys.getwindowsversion()[:3]
if CURRENT_VERS[2] > BUILD_ANSI_AVAIL:
result = True
else:
resu... | [
"def",
"is_ansi_capable",
"(",
")",
":",
"BUILD_ANSI_AVAIL",
"=",
"10586",
"# Win10 TH2",
"CURRENT_VERS",
"=",
"sys",
".",
"getwindowsversion",
"(",
")",
"[",
":",
"3",
"]",
"if",
"CURRENT_VERS",
"[",
"2",
"]",
">",
"BUILD_ANSI_AVAIL",
":",
"result",
"=",
... | Check to see whether this version of Windows is recent enough to
support "ANSI VT"" processing. | [
"Check",
"to",
"see",
"whether",
"this",
"version",
"of",
"Windows",
"is",
"recent",
"enough",
"to",
"support",
"ANSI",
"VT",
"processing",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L133-L145 | train | 64,672 |
mixmastamyk/console | console/windows.py | get_color | def get_color(name, stream=STD_OUTPUT_HANDLE):
''' Returns current colors of console.
https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo
Arguments:
name: one of ('background', 'bg', 'foreground', 'fg')
stream: Handle to stdout, stderr, etc.
... | python | def get_color(name, stream=STD_OUTPUT_HANDLE):
''' Returns current colors of console.
https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo
Arguments:
name: one of ('background', 'bg', 'foreground', 'fg')
stream: Handle to stdout, stderr, etc.
... | [
"def",
"get_color",
"(",
"name",
",",
"stream",
"=",
"STD_OUTPUT_HANDLE",
")",
":",
"stream",
"=",
"kernel32",
".",
"GetStdHandle",
"(",
"stream",
")",
"csbi",
"=",
"CONSOLE_SCREEN_BUFFER_INFO",
"(",
")",
"kernel32",
".",
"GetConsoleScreenBufferInfo",
"(",
"stre... | Returns current colors of console.
https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo
Arguments:
name: one of ('background', 'bg', 'foreground', 'fg')
stream: Handle to stdout, stderr, etc.
Returns:
int: a color id from the conho... | [
"Returns",
"current",
"colors",
"of",
"console",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L160-L185 | train | 64,673 |
mixmastamyk/console | console/windows.py | get_position | def get_position(stream=STD_OUTPUT_HANDLE):
''' Returns current position of cursor, starts at 1. '''
stream = kernel32.GetStdHandle(stream)
csbi = CONSOLE_SCREEN_BUFFER_INFO()
kernel32.GetConsoleScreenBufferInfo(stream, byref(csbi))
pos = csbi.dwCursorPosition
# zero based, add ones for compati... | python | def get_position(stream=STD_OUTPUT_HANDLE):
''' Returns current position of cursor, starts at 1. '''
stream = kernel32.GetStdHandle(stream)
csbi = CONSOLE_SCREEN_BUFFER_INFO()
kernel32.GetConsoleScreenBufferInfo(stream, byref(csbi))
pos = csbi.dwCursorPosition
# zero based, add ones for compati... | [
"def",
"get_position",
"(",
"stream",
"=",
"STD_OUTPUT_HANDLE",
")",
":",
"stream",
"=",
"kernel32",
".",
"GetStdHandle",
"(",
"stream",
")",
"csbi",
"=",
"CONSOLE_SCREEN_BUFFER_INFO",
"(",
")",
"kernel32",
".",
"GetConsoleScreenBufferInfo",
"(",
"stream",
",",
... | Returns current position of cursor, starts at 1. | [
"Returns",
"current",
"position",
"of",
"cursor",
"starts",
"at",
"1",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L188-L196 | train | 64,674 |
mixmastamyk/console | console/windows.py | set_position | def set_position(x, y, stream=STD_OUTPUT_HANDLE):
''' Sets current position of the cursor. '''
stream = kernel32.GetStdHandle(stream)
value = x + (y << 16)
kernel32.SetConsoleCursorPosition(stream, c_long(value)) | python | def set_position(x, y, stream=STD_OUTPUT_HANDLE):
''' Sets current position of the cursor. '''
stream = kernel32.GetStdHandle(stream)
value = x + (y << 16)
kernel32.SetConsoleCursorPosition(stream, c_long(value)) | [
"def",
"set_position",
"(",
"x",
",",
"y",
",",
"stream",
"=",
"STD_OUTPUT_HANDLE",
")",
":",
"stream",
"=",
"kernel32",
".",
"GetStdHandle",
"(",
"stream",
")",
"value",
"=",
"x",
"+",
"(",
"y",
"<<",
"16",
")",
"kernel32",
".",
"SetConsoleCursorPositio... | Sets current position of the cursor. | [
"Sets",
"current",
"position",
"of",
"the",
"cursor",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L199-L203 | train | 64,675 |
mixmastamyk/console | console/windows.py | get_title | def get_title():
''' Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle
'''
MAX_LEN = 256
buffer_ = create_unicode_buffer(MAX_LEN)
kernel32.GetConsoleTitleW(buffer_, MAX_LEN)
log.debug('%s', buffer_.value)
return buffer_.value | python | def get_title():
''' Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle
'''
MAX_LEN = 256
buffer_ = create_unicode_buffer(MAX_LEN)
kernel32.GetConsoleTitleW(buffer_, MAX_LEN)
log.debug('%s', buffer_.value)
return buffer_.value | [
"def",
"get_title",
"(",
")",
":",
"MAX_LEN",
"=",
"256",
"buffer_",
"=",
"create_unicode_buffer",
"(",
"MAX_LEN",
")",
"kernel32",
".",
"GetConsoleTitleW",
"(",
"buffer_",
",",
"MAX_LEN",
")",
"log",
".",
"debug",
"(",
"'%s'",
",",
"buffer_",
".",
"value"... | Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle | [
"Returns",
"console",
"title",
"string",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L206-L215 | train | 64,676 |
eagleflo/mpyq | mpyq.py | MPQArchive.read_header | def read_header(self):
"""Read the header of a MPQ archive."""
def read_mpq_header(offset=None):
if offset:
self.file.seek(offset)
data = self.file.read(32)
header = MPQFileHeader._make(
struct.unpack(MPQFileHeader.struct_format, data)... | python | def read_header(self):
"""Read the header of a MPQ archive."""
def read_mpq_header(offset=None):
if offset:
self.file.seek(offset)
data = self.file.read(32)
header = MPQFileHeader._make(
struct.unpack(MPQFileHeader.struct_format, data)... | [
"def",
"read_header",
"(",
"self",
")",
":",
"def",
"read_mpq_header",
"(",
"offset",
"=",
"None",
")",
":",
"if",
"offset",
":",
"self",
".",
"file",
".",
"seek",
"(",
"offset",
")",
"data",
"=",
"self",
".",
"file",
".",
"read",
"(",
"32",
")",
... | Read the header of a MPQ archive. | [
"Read",
"the",
"header",
"of",
"a",
"MPQ",
"archive",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L108-L147 | train | 64,677 |
eagleflo/mpyq | mpyq.py | MPQArchive.read_table | def read_table(self, table_type):
"""Read either the hash or block table of a MPQ archive."""
if table_type == 'hash':
entry_class = MPQHashTableEntry
elif table_type == 'block':
entry_class = MPQBlockTableEntry
else:
raise ValueError("Invalid table t... | python | def read_table(self, table_type):
"""Read either the hash or block table of a MPQ archive."""
if table_type == 'hash':
entry_class = MPQHashTableEntry
elif table_type == 'block':
entry_class = MPQBlockTableEntry
else:
raise ValueError("Invalid table t... | [
"def",
"read_table",
"(",
"self",
",",
"table_type",
")",
":",
"if",
"table_type",
"==",
"'hash'",
":",
"entry_class",
"=",
"MPQHashTableEntry",
"elif",
"table_type",
"==",
"'block'",
":",
"entry_class",
"=",
"MPQBlockTableEntry",
"else",
":",
"raise",
"ValueErr... | Read either the hash or block table of a MPQ archive. | [
"Read",
"either",
"the",
"hash",
"or",
"block",
"table",
"of",
"a",
"MPQ",
"archive",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L149-L172 | train | 64,678 |
eagleflo/mpyq | mpyq.py | MPQArchive.get_hash_table_entry | def get_hash_table_entry(self, filename):
"""Get the hash table entry corresponding to a given filename."""
hash_a = self._hash(filename, 'HASH_A')
hash_b = self._hash(filename, 'HASH_B')
for entry in self.hash_table:
if (entry.hash_a == hash_a and entry.hash_b == hash_b):
... | python | def get_hash_table_entry(self, filename):
"""Get the hash table entry corresponding to a given filename."""
hash_a = self._hash(filename, 'HASH_A')
hash_b = self._hash(filename, 'HASH_B')
for entry in self.hash_table:
if (entry.hash_a == hash_a and entry.hash_b == hash_b):
... | [
"def",
"get_hash_table_entry",
"(",
"self",
",",
"filename",
")",
":",
"hash_a",
"=",
"self",
".",
"_hash",
"(",
"filename",
",",
"'HASH_A'",
")",
"hash_b",
"=",
"self",
".",
"_hash",
"(",
"filename",
",",
"'HASH_B'",
")",
"for",
"entry",
"in",
"self",
... | Get the hash table entry corresponding to a given filename. | [
"Get",
"the",
"hash",
"table",
"entry",
"corresponding",
"to",
"a",
"given",
"filename",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L174-L180 | train | 64,679 |
eagleflo/mpyq | mpyq.py | MPQArchive.read_file | def read_file(self, filename, force_decompress=False):
"""Read a file from the MPQ archive."""
def decompress(data):
"""Read the compression type and decompress file data."""
compression_type = ord(data[0:1])
if compression_type == 0:
return data
... | python | def read_file(self, filename, force_decompress=False):
"""Read a file from the MPQ archive."""
def decompress(data):
"""Read the compression type and decompress file data."""
compression_type = ord(data[0:1])
if compression_type == 0:
return data
... | [
"def",
"read_file",
"(",
"self",
",",
"filename",
",",
"force_decompress",
"=",
"False",
")",
":",
"def",
"decompress",
"(",
"data",
")",
":",
"\"\"\"Read the compression type and decompress file data.\"\"\"",
"compression_type",
"=",
"ord",
"(",
"data",
"[",
"0",
... | Read a file from the MPQ archive. | [
"Read",
"a",
"file",
"from",
"the",
"MPQ",
"archive",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L182-L244 | train | 64,680 |
eagleflo/mpyq | mpyq.py | MPQArchive.extract | def extract(self):
"""Extract all the files inside the MPQ archive in memory."""
if self.files:
return dict((f, self.read_file(f)) for f in self.files)
else:
raise RuntimeError("Can't extract whole archive without listfile.") | python | def extract(self):
"""Extract all the files inside the MPQ archive in memory."""
if self.files:
return dict((f, self.read_file(f)) for f in self.files)
else:
raise RuntimeError("Can't extract whole archive without listfile.") | [
"def",
"extract",
"(",
"self",
")",
":",
"if",
"self",
".",
"files",
":",
"return",
"dict",
"(",
"(",
"f",
",",
"self",
".",
"read_file",
"(",
"f",
")",
")",
"for",
"f",
"in",
"self",
".",
"files",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
... | Extract all the files inside the MPQ archive in memory. | [
"Extract",
"all",
"the",
"files",
"inside",
"the",
"MPQ",
"archive",
"in",
"memory",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L246-L251 | train | 64,681 |
eagleflo/mpyq | mpyq.py | MPQArchive.extract_to_disk | def extract_to_disk(self):
"""Extract all files and write them to disk."""
archive_name, extension = os.path.splitext(os.path.basename(self.file.name))
if not os.path.isdir(os.path.join(os.getcwd(), archive_name)):
os.mkdir(archive_name)
os.chdir(archive_name)
for fil... | python | def extract_to_disk(self):
"""Extract all files and write them to disk."""
archive_name, extension = os.path.splitext(os.path.basename(self.file.name))
if not os.path.isdir(os.path.join(os.getcwd(), archive_name)):
os.mkdir(archive_name)
os.chdir(archive_name)
for fil... | [
"def",
"extract_to_disk",
"(",
"self",
")",
":",
"archive_name",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"file",
".",
"name",
")",
")",
"if",
"not",
"os",
".",
"path",
".... | Extract all files and write them to disk. | [
"Extract",
"all",
"files",
"and",
"write",
"them",
"to",
"disk",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L253-L262 | train | 64,682 |
eagleflo/mpyq | mpyq.py | MPQArchive.extract_files | def extract_files(self, *filenames):
"""Extract given files from the archive to disk."""
for filename in filenames:
data = self.read_file(filename)
f = open(filename, 'wb')
f.write(data or b'')
f.close() | python | def extract_files(self, *filenames):
"""Extract given files from the archive to disk."""
for filename in filenames:
data = self.read_file(filename)
f = open(filename, 'wb')
f.write(data or b'')
f.close() | [
"def",
"extract_files",
"(",
"self",
",",
"*",
"filenames",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"data",
"=",
"self",
".",
"read_file",
"(",
"filename",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"f",
".",
"write",
"(",... | Extract given files from the archive to disk. | [
"Extract",
"given",
"files",
"from",
"the",
"archive",
"to",
"disk",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L264-L270 | train | 64,683 |
eagleflo/mpyq | mpyq.py | MPQArchive._hash | def _hash(self, string, hash_type):
"""Hash a string using MPQ's hash function."""
hash_types = {
'TABLE_OFFSET': 0,
'HASH_A': 1,
'HASH_B': 2,
'TABLE': 3
}
seed1 = 0x7FED7FED
seed2 = 0xEEEEEEEE
for ch in string.upper():
... | python | def _hash(self, string, hash_type):
"""Hash a string using MPQ's hash function."""
hash_types = {
'TABLE_OFFSET': 0,
'HASH_A': 1,
'HASH_B': 2,
'TABLE': 3
}
seed1 = 0x7FED7FED
seed2 = 0xEEEEEEEE
for ch in string.upper():
... | [
"def",
"_hash",
"(",
"self",
",",
"string",
",",
"hash_type",
")",
":",
"hash_types",
"=",
"{",
"'TABLE_OFFSET'",
":",
"0",
",",
"'HASH_A'",
":",
"1",
",",
"'HASH_B'",
":",
"2",
",",
"'TABLE'",
":",
"3",
"}",
"seed1",
"=",
"0x7FED7FED",
"seed2",
"=",... | Hash a string using MPQ's hash function. | [
"Hash",
"a",
"string",
"using",
"MPQ",
"s",
"hash",
"function",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L315-L332 | train | 64,684 |
eagleflo/mpyq | mpyq.py | MPQArchive._decrypt | def _decrypt(self, data, key):
"""Decrypt hash or block table or a sector."""
seed1 = key
seed2 = 0xEEEEEEEE
result = BytesIO()
for i in range(len(data) // 4):
seed2 += self.encryption_table[0x400 + (seed1 & 0xFF)]
seed2 &= 0xFFFFFFFF
value = ... | python | def _decrypt(self, data, key):
"""Decrypt hash or block table or a sector."""
seed1 = key
seed2 = 0xEEEEEEEE
result = BytesIO()
for i in range(len(data) // 4):
seed2 += self.encryption_table[0x400 + (seed1 & 0xFF)]
seed2 &= 0xFFFFFFFF
value = ... | [
"def",
"_decrypt",
"(",
"self",
",",
"data",
",",
"key",
")",
":",
"seed1",
"=",
"key",
"seed2",
"=",
"0xEEEEEEEE",
"result",
"=",
"BytesIO",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"data",
")",
"//",
"4",
")",
":",
"seed2",
"+=",
... | Decrypt hash or block table or a sector. | [
"Decrypt",
"hash",
"or",
"block",
"table",
"or",
"a",
"sector",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L334-L352 | train | 64,685 |
eagleflo/mpyq | mpyq.py | MPQArchive._prepare_encryption_table | def _prepare_encryption_table():
"""Prepare encryption table for MPQ hash function."""
seed = 0x00100001
crypt_table = {}
for i in range(256):
index = i
for j in range(5):
seed = (seed * 125 + 3) % 0x2AAAAB
temp1 = (seed & 0xFFFF) ... | python | def _prepare_encryption_table():
"""Prepare encryption table for MPQ hash function."""
seed = 0x00100001
crypt_table = {}
for i in range(256):
index = i
for j in range(5):
seed = (seed * 125 + 3) % 0x2AAAAB
temp1 = (seed & 0xFFFF) ... | [
"def",
"_prepare_encryption_table",
"(",
")",
":",
"seed",
"=",
"0x00100001",
"crypt_table",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"256",
")",
":",
"index",
"=",
"i",
"for",
"j",
"in",
"range",
"(",
"5",
")",
":",
"seed",
"=",
"(",
"seed",... | Prepare encryption table for MPQ hash function. | [
"Prepare",
"encryption",
"table",
"for",
"MPQ",
"hash",
"function",
"."
] | ec778a454be62d5e63cae9fb16b75832a76cb9aa | https://github.com/eagleflo/mpyq/blob/ec778a454be62d5e63cae9fb16b75832a76cb9aa/mpyq.py#L354-L372 | train | 64,686 |
jamesturk/scrapelib | scrapelib/cache.py | CachingSession.key_for_request | def key_for_request(self, method, url, **kwargs):
""" Return a cache key from a given set of request parameters.
Default behavior is to return a complete URL for all GET
requests, and None otherwise.
Can be overriden if caching of non-get requests is desired.
"""
... | python | def key_for_request(self, method, url, **kwargs):
""" Return a cache key from a given set of request parameters.
Default behavior is to return a complete URL for all GET
requests, and None otherwise.
Can be overriden if caching of non-get requests is desired.
"""
... | [
"def",
"key_for_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"method",
"!=",
"'get'",
":",
"return",
"None",
"return",
"requests",
".",
"Request",
"(",
"url",
"=",
"url",
",",
"params",
"=",
"kwargs",
"."... | Return a cache key from a given set of request parameters.
Default behavior is to return a complete URL for all GET
requests, and None otherwise.
Can be overriden if caching of non-get requests is desired. | [
"Return",
"a",
"cache",
"key",
"from",
"a",
"given",
"set",
"of",
"request",
"parameters",
"."
] | dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525 | https://github.com/jamesturk/scrapelib/blob/dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525/scrapelib/cache.py#L22-L33 | train | 64,687 |
jamesturk/scrapelib | scrapelib/cache.py | CachingSession.request | def request(self, method, url, **kwargs):
""" Override, wraps Session.request in caching.
Cache is only used if key_for_request returns a valid key
and should_cache_response was true as well.
"""
# short circuit if cache isn't configured
if not self.cache_storage... | python | def request(self, method, url, **kwargs):
""" Override, wraps Session.request in caching.
Cache is only used if key_for_request returns a valid key
and should_cache_response was true as well.
"""
# short circuit if cache isn't configured
if not self.cache_storage... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"# short circuit if cache isn't configured",
"if",
"not",
"self",
".",
"cache_storage",
":",
"resp",
"=",
"super",
"(",
"CachingSession",
",",
"self",
")",
".",
"r... | Override, wraps Session.request in caching.
Cache is only used if key_for_request returns a valid key
and should_cache_response was true as well. | [
"Override",
"wraps",
"Session",
".",
"request",
"in",
"caching",
"."
] | dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525 | https://github.com/jamesturk/scrapelib/blob/dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525/scrapelib/cache.py#L43-L72 | train | 64,688 |
justanr/Flask-Transfer | flask_transfer/transfer.py | _make_destination_callable | def _make_destination_callable(dest):
"""Creates a callable out of the destination. If it's already callable,
the destination is returned. Instead, if the object is a string or a
writable object, it's wrapped in a closure to be used later.
"""
if callable(dest):
return dest
elif hasattr(... | python | def _make_destination_callable(dest):
"""Creates a callable out of the destination. If it's already callable,
the destination is returned. Instead, if the object is a string or a
writable object, it's wrapped in a closure to be used later.
"""
if callable(dest):
return dest
elif hasattr(... | [
"def",
"_make_destination_callable",
"(",
"dest",
")",
":",
"if",
"callable",
"(",
"dest",
")",
":",
"return",
"dest",
"elif",
"hasattr",
"(",
"dest",
",",
"'write'",
")",
"or",
"isinstance",
"(",
"dest",
",",
"string_types",
")",
":",
"return",
"_use_file... | Creates a callable out of the destination. If it's already callable,
the destination is returned. Instead, if the object is a string or a
writable object, it's wrapped in a closure to be used later. | [
"Creates",
"a",
"callable",
"out",
"of",
"the",
"destination",
".",
"If",
"it",
"s",
"already",
"callable",
"the",
"destination",
"is",
"returned",
".",
"Instead",
"if",
"the",
"object",
"is",
"a",
"string",
"or",
"a",
"writable",
"object",
"it",
"s",
"w... | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L15-L25 | train | 64,689 |
justanr/Flask-Transfer | flask_transfer/transfer.py | Transfer._validate | def _validate(self, filehandle, metadata, catch_all_errors=False):
"""Runs all attached validators on the provided filehandle.
In the base implmentation of Transfer, the result of `_validate` isn't
checked. Rather validators are expected to raise UploadError to report
failure.
`... | python | def _validate(self, filehandle, metadata, catch_all_errors=False):
"""Runs all attached validators on the provided filehandle.
In the base implmentation of Transfer, the result of `_validate` isn't
checked. Rather validators are expected to raise UploadError to report
failure.
`... | [
"def",
"_validate",
"(",
"self",
",",
"filehandle",
",",
"metadata",
",",
"catch_all_errors",
"=",
"False",
")",
":",
"errors",
"=",
"[",
"]",
"DEFAULT_ERROR_MSG",
"=",
"'{0!r}({1!r}, {2!r}) returned False'",
"for",
"validator",
"in",
"self",
".",
"_validators",
... | Runs all attached validators on the provided filehandle.
In the base implmentation of Transfer, the result of `_validate` isn't
checked. Rather validators are expected to raise UploadError to report
failure.
`_validate` can optionally catch all UploadErrors that occur or bail out
... | [
"Runs",
"all",
"attached",
"validators",
"on",
"the",
"provided",
"filehandle",
".",
"In",
"the",
"base",
"implmentation",
"of",
"Transfer",
"the",
"result",
"of",
"_validate",
"isn",
"t",
"checked",
".",
"Rather",
"validators",
"are",
"expected",
"to",
"raise... | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L146-L172 | train | 64,690 |
justanr/Flask-Transfer | flask_transfer/transfer.py | Transfer._preprocess | def _preprocess(self, filehandle, metadata):
"Runs all attached preprocessors on the provided filehandle."
for process in self._preprocessors:
filehandle = process(filehandle, metadata)
return filehandle | python | def _preprocess(self, filehandle, metadata):
"Runs all attached preprocessors on the provided filehandle."
for process in self._preprocessors:
filehandle = process(filehandle, metadata)
return filehandle | [
"def",
"_preprocess",
"(",
"self",
",",
"filehandle",
",",
"metadata",
")",
":",
"for",
"process",
"in",
"self",
".",
"_preprocessors",
":",
"filehandle",
"=",
"process",
"(",
"filehandle",
",",
"metadata",
")",
"return",
"filehandle"
] | Runs all attached preprocessors on the provided filehandle. | [
"Runs",
"all",
"attached",
"preprocessors",
"on",
"the",
"provided",
"filehandle",
"."
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L174-L178 | train | 64,691 |
justanr/Flask-Transfer | flask_transfer/transfer.py | Transfer._postprocess | def _postprocess(self, filehandle, metadata):
"Runs all attached postprocessors on the provided filehandle."
for process in self._postprocessors:
filehandle = process(filehandle, metadata)
return filehandle | python | def _postprocess(self, filehandle, metadata):
"Runs all attached postprocessors on the provided filehandle."
for process in self._postprocessors:
filehandle = process(filehandle, metadata)
return filehandle | [
"def",
"_postprocess",
"(",
"self",
",",
"filehandle",
",",
"metadata",
")",
":",
"for",
"process",
"in",
"self",
".",
"_postprocessors",
":",
"filehandle",
"=",
"process",
"(",
"filehandle",
",",
"metadata",
")",
"return",
"filehandle"
] | Runs all attached postprocessors on the provided filehandle. | [
"Runs",
"all",
"attached",
"postprocessors",
"on",
"the",
"provided",
"filehandle",
"."
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L180-L184 | train | 64,692 |
justanr/Flask-Transfer | flask_transfer/transfer.py | Transfer.save | def save(self, filehandle, destination=None, metadata=None,
validate=True, catch_all_errors=False, *args, **kwargs):
"""Saves the filehandle to the provided destination or the attached
default destination. Allows passing arbitrary positional and keyword
arguments to the saving mecha... | python | def save(self, filehandle, destination=None, metadata=None,
validate=True, catch_all_errors=False, *args, **kwargs):
"""Saves the filehandle to the provided destination or the attached
default destination. Allows passing arbitrary positional and keyword
arguments to the saving mecha... | [
"def",
"save",
"(",
"self",
",",
"filehandle",
",",
"destination",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"validate",
"=",
"True",
",",
"catch_all_errors",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"destination",
"=",
... | Saves the filehandle to the provided destination or the attached
default destination. Allows passing arbitrary positional and keyword
arguments to the saving mechanism
:param filehandle: werkzeug.FileStorage instance
:param dest: String path, callable or writable destination to pass the... | [
"Saves",
"the",
"filehandle",
"to",
"the",
"provided",
"destination",
"or",
"the",
"attached",
"default",
"destination",
".",
"Allows",
"passing",
"arbitrary",
"positional",
"and",
"keyword",
"arguments",
"to",
"the",
"saving",
"mechanism"
] | 075ba9edb8c8d0ea47619cc763394bbb717c2ead | https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/flask_transfer/transfer.py#L186-L219 | train | 64,693 |
mixmastamyk/console | console/detection.py | choose_palette | def choose_palette(stream=sys.stdout, basic_palette=None):
''' Make a best effort to automatically determine whether to enable
ANSI sequences, and if so, which color palettes are available.
This is the main function of the module—meant to be used unless
something more specific is needed.
... | python | def choose_palette(stream=sys.stdout, basic_palette=None):
''' Make a best effort to automatically determine whether to enable
ANSI sequences, and if so, which color palettes are available.
This is the main function of the module—meant to be used unless
something more specific is needed.
... | [
"def",
"choose_palette",
"(",
"stream",
"=",
"sys",
".",
"stdout",
",",
"basic_palette",
"=",
"None",
")",
":",
"result",
"=",
"None",
"pal",
"=",
"basic_palette",
"log",
".",
"debug",
"(",
"'console version: %s'",
",",
"__version__",
")",
"log",
".",
"deb... | Make a best effort to automatically determine whether to enable
ANSI sequences, and if so, which color palettes are available.
This is the main function of the module—meant to be used unless
something more specific is needed.
Takes the following factors into account:
- Whether... | [
"Make",
"a",
"best",
"effort",
"to",
"automatically",
"determine",
"whether",
"to",
"enable",
"ANSI",
"sequences",
"and",
"if",
"so",
"which",
"color",
"palettes",
"are",
"available",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L66-L100 | train | 64,694 |
mixmastamyk/console | console/detection.py | detect_palette_support | def detect_palette_support(basic_palette=None):
''' Returns whether we think the terminal supports basic, extended, or
truecolor. None if not able to tell.
Returns:
None or str: 'basic', 'extended', 'truecolor'
'''
result = col_init = win_enabled = None
TERM = env.TERM or '... | python | def detect_palette_support(basic_palette=None):
''' Returns whether we think the terminal supports basic, extended, or
truecolor. None if not able to tell.
Returns:
None or str: 'basic', 'extended', 'truecolor'
'''
result = col_init = win_enabled = None
TERM = env.TERM or '... | [
"def",
"detect_palette_support",
"(",
"basic_palette",
"=",
"None",
")",
":",
"result",
"=",
"col_init",
"=",
"win_enabled",
"=",
"None",
"TERM",
"=",
"env",
".",
"TERM",
"or",
"''",
"if",
"os_name",
"==",
"'nt'",
":",
"from",
".",
"windows",
"import",
"... | Returns whether we think the terminal supports basic, extended, or
truecolor. None if not able to tell.
Returns:
None or str: 'basic', 'extended', 'truecolor' | [
"Returns",
"whether",
"we",
"think",
"the",
"terminal",
"supports",
"basic",
"extended",
"or",
"truecolor",
".",
"None",
"if",
"not",
"able",
"to",
"tell",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L176-L219 | train | 64,695 |
mixmastamyk/console | console/detection.py | _find_basic_palette | def _find_basic_palette(result):
''' Find the platform-dependent 16-color basic palette.
This is used for "downgrading to the nearest color" support.
'''
pal_name = 'default (xterm)'
basic_palette = color_tables.xterm_palette4
if env.SSH_CLIENT: # fall back to xterm over ssh, info often wr... | python | def _find_basic_palette(result):
''' Find the platform-dependent 16-color basic palette.
This is used for "downgrading to the nearest color" support.
'''
pal_name = 'default (xterm)'
basic_palette = color_tables.xterm_palette4
if env.SSH_CLIENT: # fall back to xterm over ssh, info often wr... | [
"def",
"_find_basic_palette",
"(",
"result",
")",
":",
"pal_name",
"=",
"'default (xterm)'",
"basic_palette",
"=",
"color_tables",
".",
"xterm_palette4",
"if",
"env",
".",
"SSH_CLIENT",
":",
"# fall back to xterm over ssh, info often wrong",
"pal_name",
"=",
"'ssh (xterm)... | Find the platform-dependent 16-color basic palette.
This is used for "downgrading to the nearest color" support. | [
"Find",
"the",
"platform",
"-",
"dependent",
"16",
"-",
"color",
"basic",
"palette",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L266-L315 | train | 64,696 |
mixmastamyk/console | console/detection.py | get_available_palettes | def get_available_palettes(chosen_palette):
''' Given a chosen palette, returns tuple of those available,
or None when not found.
Because palette support of a particular level is almost always a
superset of lower levels, this should return all available palettes.
Returns:
... | python | def get_available_palettes(chosen_palette):
''' Given a chosen palette, returns tuple of those available,
or None when not found.
Because palette support of a particular level is almost always a
superset of lower levels, this should return all available palettes.
Returns:
... | [
"def",
"get_available_palettes",
"(",
"chosen_palette",
")",
":",
"result",
"=",
"None",
"try",
":",
"result",
"=",
"ALL_PALETTES",
"[",
":",
"ALL_PALETTES",
".",
"index",
"(",
"chosen_palette",
")",
"+",
"1",
"]",
"except",
"ValueError",
":",
"pass",
"retur... | Given a chosen palette, returns tuple of those available,
or None when not found.
Because palette support of a particular level is almost always a
superset of lower levels, this should return all available palettes.
Returns:
Boolean, None: is tty or None if not found. | [
"Given",
"a",
"chosen",
"palette",
"returns",
"tuple",
"of",
"those",
"available",
"or",
"None",
"when",
"not",
"found",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L318-L333 | train | 64,697 |
mixmastamyk/console | console/detection.py | is_a_tty | def is_a_tty(stream=sys.stdout):
''' Detect terminal or something else, such as output redirection.
Returns:
Boolean, None: is tty or None if not found.
'''
result = stream.isatty() if hasattr(stream, 'isatty') else None
log.debug(result)
return result | python | def is_a_tty(stream=sys.stdout):
''' Detect terminal or something else, such as output redirection.
Returns:
Boolean, None: is tty or None if not found.
'''
result = stream.isatty() if hasattr(stream, 'isatty') else None
log.debug(result)
return result | [
"def",
"is_a_tty",
"(",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"result",
"=",
"stream",
".",
"isatty",
"(",
")",
"if",
"hasattr",
"(",
"stream",
",",
"'isatty'",
")",
"else",
"None",
"log",
".",
"debug",
"(",
"result",
")",
"return",
"result"... | Detect terminal or something else, such as output redirection.
Returns:
Boolean, None: is tty or None if not found. | [
"Detect",
"terminal",
"or",
"something",
"else",
"such",
"as",
"output",
"redirection",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L336-L344 | train | 64,698 |
mixmastamyk/console | console/detection.py | load_x11_color_map | def load_x11_color_map(paths=X11_RGB_PATHS):
''' Load and parse X11's rgb.txt.
Loads:
x11_color_map: { name_lower: ('R', 'G', 'B') }
'''
if type(paths) is str:
paths = (paths,)
x11_color_map = color_tables.x11_color_map
for path in paths:
try:
with o... | python | def load_x11_color_map(paths=X11_RGB_PATHS):
''' Load and parse X11's rgb.txt.
Loads:
x11_color_map: { name_lower: ('R', 'G', 'B') }
'''
if type(paths) is str:
paths = (paths,)
x11_color_map = color_tables.x11_color_map
for path in paths:
try:
with o... | [
"def",
"load_x11_color_map",
"(",
"paths",
"=",
"X11_RGB_PATHS",
")",
":",
"if",
"type",
"(",
"paths",
")",
"is",
"str",
":",
"paths",
"=",
"(",
"paths",
",",
")",
"x11_color_map",
"=",
"color_tables",
".",
"x11_color_map",
"for",
"path",
"in",
"paths",
... | Load and parse X11's rgb.txt.
Loads:
x11_color_map: { name_lower: ('R', 'G', 'B') } | [
"Load",
"and",
"parse",
"X11",
"s",
"rgb",
".",
"txt",
"."
] | afe6c95d5a7b83d85376f450454e3769e4a5c3d0 | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L347-L375 | train | 64,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.