id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
39,800 | jaraco/jaraco.services | jaraco/services/__init__.py | Subprocess._get_more_data | def _get_more_data(self, file, timeout):
"""
Return data from the file, if available. If no data is received
by the timeout, then raise RuntimeError.
"""
timeout = datetime.timedelta(seconds=timeout)
timer = Stopwatch()
while timer.split() < timeout:
d... | python | def _get_more_data(self, file, timeout):
"""
Return data from the file, if available. If no data is received
by the timeout, then raise RuntimeError.
"""
timeout = datetime.timedelta(seconds=timeout)
timer = Stopwatch()
while timer.split() < timeout:
d... | [
"def",
"_get_more_data",
"(",
"self",
",",
"file",
",",
"timeout",
")",
":",
"timeout",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"timeout",
")",
"timer",
"=",
"Stopwatch",
"(",
")",
"while",
"timer",
".",
"split",
"(",
")",
"<",
"timeout... | Return data from the file, if available. If no data is received
by the timeout, then raise RuntimeError. | [
"Return",
"data",
"from",
"the",
"file",
"if",
"available",
".",
"If",
"no",
"data",
"is",
"received",
"by",
"the",
"timeout",
"then",
"raise",
"RuntimeError",
"."
] | 4ccce53541201f778035b69e9c59e41e34ee5992 | https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L233-L244 |
39,801 | jaraco/jaraco.services | jaraco/services/__init__.py | PythonService._run_env | def _run_env(self):
"""
Augment the current environment providing the PYTHONUSERBASE.
"""
env = dict(os.environ)
env.update(
getattr(self, 'env', {}),
PYTHONUSERBASE=self.env_path,
PIP_USER="1",
)
self._disable_venv(env)
... | python | def _run_env(self):
"""
Augment the current environment providing the PYTHONUSERBASE.
"""
env = dict(os.environ)
env.update(
getattr(self, 'env', {}),
PYTHONUSERBASE=self.env_path,
PIP_USER="1",
)
self._disable_venv(env)
... | [
"def",
"_run_env",
"(",
"self",
")",
":",
"env",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"env",
".",
"update",
"(",
"getattr",
"(",
"self",
",",
"'env'",
",",
"{",
"}",
")",
",",
"PYTHONUSERBASE",
"=",
"self",
".",
"env_path",
",",
"PIP_USER",... | Augment the current environment providing the PYTHONUSERBASE. | [
"Augment",
"the",
"current",
"environment",
"providing",
"the",
"PYTHONUSERBASE",
"."
] | 4ccce53541201f778035b69e9c59e41e34ee5992 | https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L350-L361 |
39,802 | jaraco/jaraco.services | jaraco/services/__init__.py | PythonService._disable_venv | def _disable_venv(self, env):
"""
Disable virtualenv and venv in the environment.
"""
venv = env.pop('VIRTUAL_ENV', None)
if venv:
venv_path, sep, env['PATH'] = env['PATH'].partition(os.pathsep) | python | def _disable_venv(self, env):
"""
Disable virtualenv and venv in the environment.
"""
venv = env.pop('VIRTUAL_ENV', None)
if venv:
venv_path, sep, env['PATH'] = env['PATH'].partition(os.pathsep) | [
"def",
"_disable_venv",
"(",
"self",
",",
"env",
")",
":",
"venv",
"=",
"env",
".",
"pop",
"(",
"'VIRTUAL_ENV'",
",",
"None",
")",
"if",
"venv",
":",
"venv_path",
",",
"sep",
",",
"env",
"[",
"'PATH'",
"]",
"=",
"env",
"[",
"'PATH'",
"]",
".",
"p... | Disable virtualenv and venv in the environment. | [
"Disable",
"virtualenv",
"and",
"venv",
"in",
"the",
"environment",
"."
] | 4ccce53541201f778035b69e9c59e41e34ee5992 | https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L363-L369 |
39,803 | jaraco/jaraco.services | jaraco/services/__init__.py | PythonService.create_env | def create_env(self):
"""
Create a PEP-370 environment
"""
root = path.Path(os.environ.get('SERVICES_ROOT', 'services'))
self.env_path = (root / self.name).abspath()
cmd = [
self.python,
'-c', 'import site; print(site.getusersitepackages())',
... | python | def create_env(self):
"""
Create a PEP-370 environment
"""
root = path.Path(os.environ.get('SERVICES_ROOT', 'services'))
self.env_path = (root / self.name).abspath()
cmd = [
self.python,
'-c', 'import site; print(site.getusersitepackages())',
... | [
"def",
"create_env",
"(",
"self",
")",
":",
"root",
"=",
"path",
".",
"Path",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'SERVICES_ROOT'",
",",
"'services'",
")",
")",
"self",
".",
"env_path",
"=",
"(",
"root",
"/",
"self",
".",
"name",
")",
".",... | Create a PEP-370 environment | [
"Create",
"a",
"PEP",
"-",
"370",
"environment"
] | 4ccce53541201f778035b69e9c59e41e34ee5992 | https://github.com/jaraco/jaraco.services/blob/4ccce53541201f778035b69e9c59e41e34ee5992/jaraco/services/__init__.py#L371-L383 |
39,804 | objectrocket/python-client | objectrocket/instances/mongodb.py | MongodbInstance.compaction | def compaction(self, request_compaction=False):
"""Retrieve a report on, or request compaction for this instance.
:param bool request_compaction: A boolean indicating whether or not to request compaction.
"""
url = self._service_url + 'compaction/'
if request_compaction:
... | python | def compaction(self, request_compaction=False):
"""Retrieve a report on, or request compaction for this instance.
:param bool request_compaction: A boolean indicating whether or not to request compaction.
"""
url = self._service_url + 'compaction/'
if request_compaction:
... | [
"def",
"compaction",
"(",
"self",
",",
"request_compaction",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"_service_url",
"+",
"'compaction/'",
"if",
"request_compaction",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"*",
"*",
"self"... | Retrieve a report on, or request compaction for this instance.
:param bool request_compaction: A boolean indicating whether or not to request compaction. | [
"Retrieve",
"a",
"report",
"on",
"or",
"request",
"compaction",
"for",
"this",
"instance",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L48-L60 |
39,805 | objectrocket/python-client | objectrocket/instances/mongodb.py | MongodbInstance.get_authenticated_connection | def get_authenticated_connection(self, user, passwd, db='admin', ssl=True):
"""Get an authenticated connection to this instance.
:param str user: The username to use for authentication.
:param str passwd: The password to use for authentication.
:param str db: The name of the database to... | python | def get_authenticated_connection(self, user, passwd, db='admin', ssl=True):
"""Get an authenticated connection to this instance.
:param str user: The username to use for authentication.
:param str passwd: The password to use for authentication.
:param str db: The name of the database to... | [
"def",
"get_authenticated_connection",
"(",
"self",
",",
"user",
",",
"passwd",
",",
"db",
"=",
"'admin'",
",",
"ssl",
"=",
"True",
")",
":",
"# Attempt to establish an authenticated connection.",
"try",
":",
"connection",
"=",
"self",
".",
"get_connection",
"(",
... | Get an authenticated connection to this instance.
:param str user: The username to use for authentication.
:param str passwd: The password to use for authentication.
:param str db: The name of the database to authenticate against. Defaults to ``'Admin'``.
:param bool ssl: Use SSL/TLS if... | [
"Get",
"an",
"authenticated",
"connection",
"to",
"this",
"instance",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L62-L80 |
39,806 | objectrocket/python-client | objectrocket/instances/mongodb.py | MongodbInstance.shards | def shards(self, add_shard=False):
"""Get a list of shards belonging to this instance.
:param bool add_shard: A boolean indicating whether to add a new shard to the specified
instance.
"""
url = self._service_url + 'shards/'
if add_shard:
response = reque... | python | def shards(self, add_shard=False):
"""Get a list of shards belonging to this instance.
:param bool add_shard: A boolean indicating whether to add a new shard to the specified
instance.
"""
url = self._service_url + 'shards/'
if add_shard:
response = reque... | [
"def",
"shards",
"(",
"self",
",",
"add_shard",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"_service_url",
"+",
"'shards/'",
"if",
"add_shard",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"*",
"*",
"self",
".",
"_instances",
... | Get a list of shards belonging to this instance.
:param bool add_shard: A boolean indicating whether to add a new shard to the specified
instance. | [
"Get",
"a",
"list",
"of",
"shards",
"belonging",
"to",
"this",
"instance",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L90-L102 |
39,807 | objectrocket/python-client | objectrocket/instances/mongodb.py | MongodbInstance.new_relic_stats | def new_relic_stats(self):
"""
Get stats for this instance.
"""
if self._new_relic_stats is None:
# if this is a sharded instance, fetch shard stats in parallel
if self.type == 'mongodb_sharded':
shards = [Shard(self.name, self._service_url + 'shar... | python | def new_relic_stats(self):
"""
Get stats for this instance.
"""
if self._new_relic_stats is None:
# if this is a sharded instance, fetch shard stats in parallel
if self.type == 'mongodb_sharded':
shards = [Shard(self.name, self._service_url + 'shar... | [
"def",
"new_relic_stats",
"(",
"self",
")",
":",
"if",
"self",
".",
"_new_relic_stats",
"is",
"None",
":",
"# if this is a sharded instance, fetch shard stats in parallel",
"if",
"self",
".",
"type",
"==",
"'mongodb_sharded'",
":",
"shards",
"=",
"[",
"Shard",
"(",
... | Get stats for this instance. | [
"Get",
"stats",
"for",
"this",
"instance",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L110-L145 |
39,808 | objectrocket/python-client | objectrocket/instances/mongodb.py | MongodbInstance._rollup_shard_stats_to_instance_stats | def _rollup_shard_stats_to_instance_stats(self, shard_stats):
"""
roll up all shard stats to instance level stats
:param shard_stats: dict of {shard_name: shard level stats}
"""
instance_stats = {}
opcounters_per_node = []
# aggregate replication_lag
ins... | python | def _rollup_shard_stats_to_instance_stats(self, shard_stats):
"""
roll up all shard stats to instance level stats
:param shard_stats: dict of {shard_name: shard level stats}
"""
instance_stats = {}
opcounters_per_node = []
# aggregate replication_lag
ins... | [
"def",
"_rollup_shard_stats_to_instance_stats",
"(",
"self",
",",
"shard_stats",
")",
":",
"instance_stats",
"=",
"{",
"}",
"opcounters_per_node",
"=",
"[",
"]",
"# aggregate replication_lag",
"instance_stats",
"[",
"'replication_lag'",
"]",
"=",
"max",
"(",
"map",
... | roll up all shard stats to instance level stats
:param shard_stats: dict of {shard_name: shard level stats} | [
"roll",
"up",
"all",
"shard",
"stats",
"to",
"instance",
"level",
"stats"
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L147-L174 |
39,809 | objectrocket/python-client | objectrocket/instances/mongodb.py | MongodbInstance._compile_new_relic_stats | def _compile_new_relic_stats(self, stats_this_second, stats_next_second):
"""
from instance 'stats_this_second' and instance 'stats_next_second', compute some per
second stats metrics and other aggregated metrics
:param dict stats_this_second:
:param dict stats_next_second:
... | python | def _compile_new_relic_stats(self, stats_this_second, stats_next_second):
"""
from instance 'stats_this_second' and instance 'stats_next_second', compute some per
second stats metrics and other aggregated metrics
:param dict stats_this_second:
:param dict stats_next_second:
... | [
"def",
"_compile_new_relic_stats",
"(",
"self",
",",
"stats_this_second",
",",
"stats_next_second",
")",
":",
"server_statistics_per_second",
"=",
"{",
"}",
"opcounters_per_node_per_second",
"=",
"[",
"]",
"for",
"subdoc",
"in",
"[",
"\"opcounters\"",
",",
"\"network\... | from instance 'stats_this_second' and instance 'stats_next_second', compute some per
second stats metrics and other aggregated metrics
:param dict stats_this_second:
:param dict stats_next_second:
:return: compiled instance stats that has metrics
{'opcounters_per_node_per_secon... | [
"from",
"instance",
"stats_this_second",
"and",
"instance",
"stats_next_second",
"compute",
"some",
"per",
"second",
"stats",
"metrics",
"and",
"other",
"aggregated",
"metrics"
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L176-L213 |
39,810 | objectrocket/python-client | objectrocket/instances/mongodb.py | MongodbInstance.get_stepdown_window | def get_stepdown_window(self):
"""Get information on this instance's stepdown window."""
url = self._service_url + 'stepdown/'
response = requests.get(url, **self._instances._default_request_kwargs)
return response.json() | python | def get_stepdown_window(self):
"""Get information on this instance's stepdown window."""
url = self._service_url + 'stepdown/'
response = requests.get(url, **self._instances._default_request_kwargs)
return response.json() | [
"def",
"get_stepdown_window",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_service_url",
"+",
"'stepdown/'",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"*",
"*",
"self",
".",
"_instances",
".",
"_default_request_kwargs",
")",
"return",
... | Get information on this instance's stepdown window. | [
"Get",
"information",
"on",
"this",
"instance",
"s",
"stepdown",
"window",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L221-L225 |
39,811 | objectrocket/python-client | objectrocket/instances/mongodb.py | MongodbInstance.set_stepdown_window | def set_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True):
"""Set the stepdown window for this instance.
Date times are assumed to be UTC, so use UTC date times.
:param datetime.datetime start: The datetime which the stepdown window is to open.
:param datetim... | python | def set_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True):
"""Set the stepdown window for this instance.
Date times are assumed to be UTC, so use UTC date times.
:param datetime.datetime start: The datetime which the stepdown window is to open.
:param datetim... | [
"def",
"set_stepdown_window",
"(",
"self",
",",
"start",
",",
"end",
",",
"enabled",
"=",
"True",
",",
"scheduled",
"=",
"True",
",",
"weekly",
"=",
"True",
")",
":",
"# Ensure a logical start and endtime is requested.",
"if",
"not",
"start",
"<",
"end",
":",
... | Set the stepdown window for this instance.
Date times are assumed to be UTC, so use UTC date times.
:param datetime.datetime start: The datetime which the stepdown window is to open.
:param datetime.datetime end: The datetime which the stepdown window is to close.
:param bool enabled: ... | [
"Set",
"the",
"stepdown",
"window",
"for",
"this",
"instance",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/mongodb.py#L228-L262 |
39,812 | tradenity/python-sdk | tradenity/resources/payment_card.py | PaymentCard.brand | def brand(self, brand):
"""Sets the brand of this PaymentCard.
:param brand: The brand of this PaymentCard.
:type: str
"""
allowed_values = ["visa", "mastercard", "americanExpress", "discover"]
if brand is not None and brand not in allowed_values:
raise Valu... | python | def brand(self, brand):
"""Sets the brand of this PaymentCard.
:param brand: The brand of this PaymentCard.
:type: str
"""
allowed_values = ["visa", "mastercard", "americanExpress", "discover"]
if brand is not None and brand not in allowed_values:
raise Valu... | [
"def",
"brand",
"(",
"self",
",",
"brand",
")",
":",
"allowed_values",
"=",
"[",
"\"visa\"",
",",
"\"mastercard\"",
",",
"\"americanExpress\"",
",",
"\"discover\"",
"]",
"if",
"brand",
"is",
"not",
"None",
"and",
"brand",
"not",
"in",
"allowed_values",
":",
... | Sets the brand of this PaymentCard.
:param brand: The brand of this PaymentCard.
:type: str | [
"Sets",
"the",
"brand",
"of",
"this",
"PaymentCard",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/payment_card.py#L253-L267 |
39,813 | orbeckst/RecSQL | recsql/export.py | latex_quote | def latex_quote(s):
"""Quote special characters for LaTeX.
(Incomplete, currently only deals with underscores, dollar and hash.)
"""
special = {'_':r'\_', '$':r'\$', '#':r'\#'}
s = str(s)
for char,repl in special.items():
new = s.replace(char, repl)
s = new[:]
return s | python | def latex_quote(s):
"""Quote special characters for LaTeX.
(Incomplete, currently only deals with underscores, dollar and hash.)
"""
special = {'_':r'\_', '$':r'\$', '#':r'\#'}
s = str(s)
for char,repl in special.items():
new = s.replace(char, repl)
s = new[:]
return s | [
"def",
"latex_quote",
"(",
"s",
")",
":",
"special",
"=",
"{",
"'_'",
":",
"r'\\_'",
",",
"'$'",
":",
"r'\\$'",
",",
"'#'",
":",
"r'\\#'",
"}",
"s",
"=",
"str",
"(",
"s",
")",
"for",
"char",
",",
"repl",
"in",
"special",
".",
"items",
"(",
")",... | Quote special characters for LaTeX.
(Incomplete, currently only deals with underscores, dollar and hash.) | [
"Quote",
"special",
"characters",
"for",
"LaTeX",
"."
] | 6acbf821022361719391697c9c2f0822f9f8022a | https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/export.py#L38-L48 |
39,814 | Aluriak/bubble-tools | bubbletools/_bubble.py | tree_to_file | def tree_to_file(tree:'BubbleTree', outfile:str):
"""Compute the bubble representation of given power graph,
and push it into given file."""
with open(outfile, 'w') as fd:
fd.write(tree_to_bubble(tree)) | python | def tree_to_file(tree:'BubbleTree', outfile:str):
"""Compute the bubble representation of given power graph,
and push it into given file."""
with open(outfile, 'w') as fd:
fd.write(tree_to_bubble(tree)) | [
"def",
"tree_to_file",
"(",
"tree",
":",
"'BubbleTree'",
",",
"outfile",
":",
"str",
")",
":",
"with",
"open",
"(",
"outfile",
",",
"'w'",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"tree_to_bubble",
"(",
"tree",
")",
")"
] | Compute the bubble representation of given power graph,
and push it into given file. | [
"Compute",
"the",
"bubble",
"representation",
"of",
"given",
"power",
"graph",
"and",
"push",
"it",
"into",
"given",
"file",
"."
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/_bubble.py#L1-L5 |
39,815 | Aluriak/bubble-tools | bubbletools/_bubble.py | lines_from_tree | def lines_from_tree(tree, nodes_and_set:bool=False) -> iter:
"""Yield lines of bubble describing given BubbleTree"""
NODE = 'NODE\t{}'
INCL = 'IN\t{}\t{}'
EDGE = 'EDGE\t{}\t{}\t1.0'
SET = 'SET\t{}'
if nodes_and_set:
for node in tree.nodes():
yield NODE.format(node)
... | python | def lines_from_tree(tree, nodes_and_set:bool=False) -> iter:
"""Yield lines of bubble describing given BubbleTree"""
NODE = 'NODE\t{}'
INCL = 'IN\t{}\t{}'
EDGE = 'EDGE\t{}\t{}\t1.0'
SET = 'SET\t{}'
if nodes_and_set:
for node in tree.nodes():
yield NODE.format(node)
... | [
"def",
"lines_from_tree",
"(",
"tree",
",",
"nodes_and_set",
":",
"bool",
"=",
"False",
")",
"->",
"iter",
":",
"NODE",
"=",
"'NODE\\t{}'",
"INCL",
"=",
"'IN\\t{}\\t{}'",
"EDGE",
"=",
"'EDGE\\t{}\\t{}\\t1.0'",
"SET",
"=",
"'SET\\t{}'",
"if",
"nodes_and_set",
"... | Yield lines of bubble describing given BubbleTree | [
"Yield",
"lines",
"of",
"bubble",
"describing",
"given",
"BubbleTree"
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/_bubble.py#L16-L36 |
39,816 | inveniosoftware-attic/invenio-utils | invenio_utils/forms.py | TimeField.process_formdata | def process_formdata(self, valuelist):
"""Join time string."""
if valuelist:
time_str = u' '.join(valuelist)
try:
timetuple = time.strptime(time_str, self.format)
self.data = datetime.time(*timetuple[3:6])
except ValueError:
... | python | def process_formdata(self, valuelist):
"""Join time string."""
if valuelist:
time_str = u' '.join(valuelist)
try:
timetuple = time.strptime(time_str, self.format)
self.data = datetime.time(*timetuple[3:6])
except ValueError:
... | [
"def",
"process_formdata",
"(",
"self",
",",
"valuelist",
")",
":",
"if",
"valuelist",
":",
"time_str",
"=",
"u' '",
".",
"join",
"(",
"valuelist",
")",
"try",
":",
"timetuple",
"=",
"time",
".",
"strptime",
"(",
"time_str",
",",
"self",
".",
"format",
... | Join time string. | [
"Join",
"time",
"string",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/forms.py#L92-L101 |
39,817 | inveniosoftware-attic/invenio-utils | invenio_utils/forms.py | InvenioBaseForm.validate_csrf_token | def validate_csrf_token(self, field):
"""Disable CRSF proection during testing."""
if current_app.testing:
return
super(InvenioBaseForm, self).validate_csrf_token(field) | python | def validate_csrf_token(self, field):
"""Disable CRSF proection during testing."""
if current_app.testing:
return
super(InvenioBaseForm, self).validate_csrf_token(field) | [
"def",
"validate_csrf_token",
"(",
"self",
",",
"field",
")",
":",
"if",
"current_app",
".",
"testing",
":",
"return",
"super",
"(",
"InvenioBaseForm",
",",
"self",
")",
".",
"validate_csrf_token",
"(",
"field",
")"
] | Disable CRSF proection during testing. | [
"Disable",
"CRSF",
"proection",
"during",
"testing",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/forms.py#L370-L374 |
39,818 | wdbm/abstraction | abstraction.py | load_exchange_word_vectors | def load_exchange_word_vectors(
filename = "database.db",
maximum_number_of_events = None
):
"""
Load exchange data and return dataset.
"""
log.info("load word vectors of database {filename}".format(
filename = filename
))
# Ensure that the database exists.
... | python | def load_exchange_word_vectors(
filename = "database.db",
maximum_number_of_events = None
):
"""
Load exchange data and return dataset.
"""
log.info("load word vectors of database {filename}".format(
filename = filename
))
# Ensure that the database exists.
... | [
"def",
"load_exchange_word_vectors",
"(",
"filename",
"=",
"\"database.db\"",
",",
"maximum_number_of_events",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"load word vectors of database {filename}\"",
".",
"format",
"(",
"filename",
"=",
"filename",
")",
")",
... | Load exchange data and return dataset. | [
"Load",
"exchange",
"data",
"and",
"return",
"dataset",
"."
] | 58c81e73954cc6b4cd2f79b2216467528a96376b | https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L314-L373 |
39,819 | wdbm/abstraction | abstraction.py | load_HEP_data | def load_HEP_data(
ROOT_filename = "output.root",
tree_name = "nominal",
maximum_number_of_events = None
):
"""
Load HEP data and return dataset.
"""
ROOT_file = open_ROOT_file(ROOT_filename)
tree = ROOT_file.Get(tree_name)
number_of_e... | python | def load_HEP_data(
ROOT_filename = "output.root",
tree_name = "nominal",
maximum_number_of_events = None
):
"""
Load HEP data and return dataset.
"""
ROOT_file = open_ROOT_file(ROOT_filename)
tree = ROOT_file.Get(tree_name)
number_of_e... | [
"def",
"load_HEP_data",
"(",
"ROOT_filename",
"=",
"\"output.root\"",
",",
"tree_name",
"=",
"\"nominal\"",
",",
"maximum_number_of_events",
"=",
"None",
")",
":",
"ROOT_file",
"=",
"open_ROOT_file",
"(",
"ROOT_filename",
")",
"tree",
"=",
"ROOT_file",
".",
"Get",... | Load HEP data and return dataset. | [
"Load",
"HEP",
"data",
"and",
"return",
"dataset",
"."
] | 58c81e73954cc6b4cd2f79b2216467528a96376b | https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L408-L480 |
39,820 | wdbm/abstraction | abstraction.py | sentiment | def sentiment(
text = None,
confidence = False
):
"""
This function accepts a string text input. It calculates the sentiment of
the text, "pos" or "neg". By default, it returns this calculated sentiment.
If selected, it returns a tuple of the calculated sentiment and the
classifica... | python | def sentiment(
text = None,
confidence = False
):
"""
This function accepts a string text input. It calculates the sentiment of
the text, "pos" or "neg". By default, it returns this calculated sentiment.
If selected, it returns a tuple of the calculated sentiment and the
classifica... | [
"def",
"sentiment",
"(",
"text",
"=",
"None",
",",
"confidence",
"=",
"False",
")",
":",
"try",
":",
"words",
"=",
"text",
".",
"split",
"(",
"\" \"",
")",
"# Remove empty strings.",
"words",
"=",
"[",
"word",
"for",
"word",
"in",
"words",
"if",
"word"... | This function accepts a string text input. It calculates the sentiment of
the text, "pos" or "neg". By default, it returns this calculated sentiment.
If selected, it returns a tuple of the calculated sentiment and the
classificaton confidence. | [
"This",
"function",
"accepts",
"a",
"string",
"text",
"input",
".",
"It",
"calculates",
"the",
"sentiment",
"of",
"the",
"text",
"pos",
"or",
"neg",
".",
"By",
"default",
"it",
"returns",
"this",
"calculated",
"sentiment",
".",
"If",
"selected",
"it",
"ret... | 58c81e73954cc6b4cd2f79b2216467528a96376b | https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L1930-L1956 |
39,821 | wdbm/abstraction | abstraction.py | Tweets.usernames | def usernames(
self
):
"""
This function returns the list of unique usernames corresponding to the
tweets stored in self.
"""
try:
return list(set([tweet.username for tweet in self]))
except:
log.error("error -- possibly a problem w... | python | def usernames(
self
):
"""
This function returns the list of unique usernames corresponding to the
tweets stored in self.
"""
try:
return list(set([tweet.username for tweet in self]))
except:
log.error("error -- possibly a problem w... | [
"def",
"usernames",
"(",
"self",
")",
":",
"try",
":",
"return",
"list",
"(",
"set",
"(",
"[",
"tweet",
".",
"username",
"for",
"tweet",
"in",
"self",
"]",
")",
")",
"except",
":",
"log",
".",
"error",
"(",
"\"error -- possibly a problem with tweets stored... | This function returns the list of unique usernames corresponding to the
tweets stored in self. | [
"This",
"function",
"returns",
"the",
"list",
"of",
"unique",
"usernames",
"corresponding",
"to",
"the",
"tweets",
"stored",
"in",
"self",
"."
] | 58c81e73954cc6b4cd2f79b2216467528a96376b | https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L824-L834 |
39,822 | wdbm/abstraction | abstraction.py | Tweets.user_sentiments | def user_sentiments(
self,
username = None
):
"""
This function returns a list of all sentiments of the tweets of a
specified user.
"""
try:
return [tweet.sentiment for tweet in self if tweet.username == username]
except:
log... | python | def user_sentiments(
self,
username = None
):
"""
This function returns a list of all sentiments of the tweets of a
specified user.
"""
try:
return [tweet.sentiment for tweet in self if tweet.username == username]
except:
log... | [
"def",
"user_sentiments",
"(",
"self",
",",
"username",
"=",
"None",
")",
":",
"try",
":",
"return",
"[",
"tweet",
".",
"sentiment",
"for",
"tweet",
"in",
"self",
"if",
"tweet",
".",
"username",
"==",
"username",
"]",
"except",
":",
"log",
".",
"error"... | This function returns a list of all sentiments of the tweets of a
specified user. | [
"This",
"function",
"returns",
"a",
"list",
"of",
"all",
"sentiments",
"of",
"the",
"tweets",
"of",
"a",
"specified",
"user",
"."
] | 58c81e73954cc6b4cd2f79b2216467528a96376b | https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L836-L848 |
39,823 | wdbm/abstraction | abstraction.py | Tweets.user_sentiments_most_frequent | def user_sentiments_most_frequent(
self,
username = None,
single_most_frequent = True
):
"""
This function returns the most frequent calculated sentiments expressed
in tweets of a specified user. By default, the single most frequent
sentiment i... | python | def user_sentiments_most_frequent(
self,
username = None,
single_most_frequent = True
):
"""
This function returns the most frequent calculated sentiments expressed
in tweets of a specified user. By default, the single most frequent
sentiment i... | [
"def",
"user_sentiments_most_frequent",
"(",
"self",
",",
"username",
"=",
"None",
",",
"single_most_frequent",
"=",
"True",
")",
":",
"try",
":",
"sentiment_frequencies",
"=",
"collections",
".",
"Counter",
"(",
"self",
".",
"user_sentiments",
"(",
"username",
... | This function returns the most frequent calculated sentiments expressed
in tweets of a specified user. By default, the single most frequent
sentiment is returned. All sentiments with their corresponding
frequencies can be returned also. | [
"This",
"function",
"returns",
"the",
"most",
"frequent",
"calculated",
"sentiments",
"expressed",
"in",
"tweets",
"of",
"a",
"specified",
"user",
".",
"By",
"default",
"the",
"single",
"most",
"frequent",
"sentiment",
"is",
"returned",
".",
"All",
"sentiments",... | 58c81e73954cc6b4cd2f79b2216467528a96376b | https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L850-L871 |
39,824 | wdbm/abstraction | abstraction.py | Tweets.users_sentiments_single_most_frequent | def users_sentiments_single_most_frequent(
self,
usernames = None,
):
"""
This function returns the single most frequent calculated sentiment
expressed by all stored users or by a list of specified users as a
dictionary.
"""
users_sentiments_single... | python | def users_sentiments_single_most_frequent(
self,
usernames = None,
):
"""
This function returns the single most frequent calculated sentiment
expressed by all stored users or by a list of specified users as a
dictionary.
"""
users_sentiments_single... | [
"def",
"users_sentiments_single_most_frequent",
"(",
"self",
",",
"usernames",
"=",
"None",
",",
")",
":",
"users_sentiments_single_most_frequent",
"=",
"dict",
"(",
")",
"if",
"usernames",
"is",
"None",
":",
"usernames",
"=",
"self",
".",
"usernames",
"(",
")",... | This function returns the single most frequent calculated sentiment
expressed by all stored users or by a list of specified users as a
dictionary. | [
"This",
"function",
"returns",
"the",
"single",
"most",
"frequent",
"calculated",
"sentiment",
"expressed",
"by",
"all",
"stored",
"users",
"or",
"by",
"a",
"list",
"of",
"specified",
"users",
"as",
"a",
"dictionary",
"."
] | 58c81e73954cc6b4cd2f79b2216467528a96376b | https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L873-L895 |
39,825 | trevisanj/a99 | a99/textinterface.py | format_progress | def format_progress(i, n):
"""Returns string containing a progress bar, a percentage, etc."""
if n == 0:
fraction = 0
else:
fraction = float(i)/n
LEN_BAR = 25
num_plus = int(round(fraction*LEN_BAR))
s_plus = '+'*num_plus
s_point = '.'*(LEN_BAR-num_plus)
return '... | python | def format_progress(i, n):
"""Returns string containing a progress bar, a percentage, etc."""
if n == 0:
fraction = 0
else:
fraction = float(i)/n
LEN_BAR = 25
num_plus = int(round(fraction*LEN_BAR))
s_plus = '+'*num_plus
s_point = '.'*(LEN_BAR-num_plus)
return '... | [
"def",
"format_progress",
"(",
"i",
",",
"n",
")",
":",
"if",
"n",
"==",
"0",
":",
"fraction",
"=",
"0",
"else",
":",
"fraction",
"=",
"float",
"(",
"i",
")",
"/",
"n",
"LEN_BAR",
"=",
"25",
"num_plus",
"=",
"int",
"(",
"round",
"(",
"fraction",
... | Returns string containing a progress bar, a percentage, etc. | [
"Returns",
"string",
"containing",
"a",
"progress",
"bar",
"a",
"percentage",
"etc",
"."
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/textinterface.py#L284-L294 |
39,826 | trevisanj/a99 | a99/textinterface.py | _format_exe_info | def _format_exe_info(py_len, exeinfo, format, indlevel):
"""Renders ExeInfo object in specified format"""
ret = []
ind = " " * indlevel * NIND if format.startswith("text") else ""
if format == "markdown-list":
for si in exeinfo:
ret.append(" - `{0!s}`: {1!s}".format(si.filenam... | python | def _format_exe_info(py_len, exeinfo, format, indlevel):
"""Renders ExeInfo object in specified format"""
ret = []
ind = " " * indlevel * NIND if format.startswith("text") else ""
if format == "markdown-list":
for si in exeinfo:
ret.append(" - `{0!s}`: {1!s}".format(si.filenam... | [
"def",
"_format_exe_info",
"(",
"py_len",
",",
"exeinfo",
",",
"format",
",",
"indlevel",
")",
":",
"ret",
"=",
"[",
"]",
"ind",
"=",
"\" \"",
"*",
"indlevel",
"*",
"NIND",
"if",
"format",
".",
"startswith",
"(",
"\"text\"",
")",
"else",
"\"\"",
"if",
... | Renders ExeInfo object in specified format | [
"Renders",
"ExeInfo",
"object",
"in",
"specified",
"format"
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/textinterface.py#L301-L329 |
39,827 | koenedaele/pyramid_skosprovider | pyramid_skosprovider/renderers.py | _map_relation | def _map_relation(c, language='any'):
"""
Map related concept or collection, leaving out the relations.
:param c: the concept or collection to map
:param string language: Language to render the relation's label in
:rtype: :class:`dict`
"""
label = c.label(language)
return {
'id'... | python | def _map_relation(c, language='any'):
"""
Map related concept or collection, leaving out the relations.
:param c: the concept or collection to map
:param string language: Language to render the relation's label in
:rtype: :class:`dict`
"""
label = c.label(language)
return {
'id'... | [
"def",
"_map_relation",
"(",
"c",
",",
"language",
"=",
"'any'",
")",
":",
"label",
"=",
"c",
".",
"label",
"(",
"language",
")",
"return",
"{",
"'id'",
":",
"c",
".",
"id",
",",
"'type'",
":",
"c",
".",
"type",
",",
"'uri'",
":",
"c",
".",
"ur... | Map related concept or collection, leaving out the relations.
:param c: the concept or collection to map
:param string language: Language to render the relation's label in
:rtype: :class:`dict` | [
"Map",
"related",
"concept",
"or",
"collection",
"leaving",
"out",
"the",
"relations",
"."
] | 3affdb53cac7ad01bf3656ecd4c4d7ad9b4948b6 | https://github.com/koenedaele/pyramid_skosprovider/blob/3affdb53cac7ad01bf3656ecd4c4d7ad9b4948b6/pyramid_skosprovider/renderers.py#L103-L117 |
39,828 | blockadeio/analyst_toolbench | blockade/libs/indicators.py | IndicatorClient.add_indicators | def add_indicators(self, indicators=list(), private=False, tags=list()):
"""Add indicators to the remote instance."""
if len(indicators) == 0:
raise Exception("No indicators were identified.")
self.logger.debug("Checking {} indicators".format(len(indicators)))
cleaned = clean... | python | def add_indicators(self, indicators=list(), private=False, tags=list()):
"""Add indicators to the remote instance."""
if len(indicators) == 0:
raise Exception("No indicators were identified.")
self.logger.debug("Checking {} indicators".format(len(indicators)))
cleaned = clean... | [
"def",
"add_indicators",
"(",
"self",
",",
"indicators",
"=",
"list",
"(",
")",
",",
"private",
"=",
"False",
",",
"tags",
"=",
"list",
"(",
")",
")",
":",
"if",
"len",
"(",
"indicators",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"No indicato... | Add indicators to the remote instance. | [
"Add",
"indicators",
"to",
"the",
"remote",
"instance",
"."
] | 159b6f8cf8a91c5ff050f1579636ea90ab269863 | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/libs/indicators.py#L22-L69 |
39,829 | blockadeio/analyst_toolbench | blockade/libs/indicators.py | IndicatorClient.get_indicators | def get_indicators(self):
"""List indicators available on the remote instance."""
response = self._get('', 'get-indicators')
response['message'] = "%i indicators:\n%s" % (
len(response['indicators']),
"\n".join(response['indicators'])
)
return response | python | def get_indicators(self):
"""List indicators available on the remote instance."""
response = self._get('', 'get-indicators')
response['message'] = "%i indicators:\n%s" % (
len(response['indicators']),
"\n".join(response['indicators'])
)
return response | [
"def",
"get_indicators",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_get",
"(",
"''",
",",
"'get-indicators'",
")",
"response",
"[",
"'message'",
"]",
"=",
"\"%i indicators:\\n%s\"",
"%",
"(",
"len",
"(",
"response",
"[",
"'indicators'",
"]",
")... | List indicators available on the remote instance. | [
"List",
"indicators",
"available",
"on",
"the",
"remote",
"instance",
"."
] | 159b6f8cf8a91c5ff050f1579636ea90ab269863 | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/libs/indicators.py#L71-L78 |
39,830 | orbeckst/RecSQL | recsql/convert.py | besttype | def besttype(x, encoding="utf-8", percentify=True):
"""Convert string x to the most useful type, i.e. int, float or unicode string.
If x is a quoted string (single or double quotes) then the quotes are
stripped and the enclosed string returned. The string can contain any
number of quotes, it is only im... | python | def besttype(x, encoding="utf-8", percentify=True):
"""Convert string x to the most useful type, i.e. int, float or unicode string.
If x is a quoted string (single or double quotes) then the quotes are
stripped and the enclosed string returned. The string can contain any
number of quotes, it is only im... | [
"def",
"besttype",
"(",
"x",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"percentify",
"=",
"True",
")",
":",
"def",
"unicodify",
"(",
"x",
")",
":",
"return",
"to_unicode",
"(",
"x",
",",
"encoding",
")",
"def",
"percent",
"(",
"x",
")",
":",
"try",
"... | Convert string x to the most useful type, i.e. int, float or unicode string.
If x is a quoted string (single or double quotes) then the quotes are
stripped and the enclosed string returned. The string can contain any
number of quotes, it is only important that it begins and ends with either
single or d... | [
"Convert",
"string",
"x",
"to",
"the",
"most",
"useful",
"type",
"i",
".",
"e",
".",
"int",
"float",
"or",
"unicode",
"string",
"."
] | 6acbf821022361719391697c9c2f0822f9f8022a | https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/convert.py#L169-L214 |
39,831 | cdumay/kser | src/kser/controller.py | BaseController._onmessage | def _onmessage(cls, kmsg):
""" Call on received message
:param kser.schemas.Message kmsg: Kafka message
:return: Kafka message
:rtype: kser.schemas.Message
"""
logger.debug(
"{}.ReceivedMessage {}[{}]".format(
cls.__name__, kmsg.entrypoint, km... | python | def _onmessage(cls, kmsg):
""" Call on received message
:param kser.schemas.Message kmsg: Kafka message
:return: Kafka message
:rtype: kser.schemas.Message
"""
logger.debug(
"{}.ReceivedMessage {}[{}]".format(
cls.__name__, kmsg.entrypoint, km... | [
"def",
"_onmessage",
"(",
"cls",
",",
"kmsg",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}.ReceivedMessage {}[{}]\"",
".",
"format",
"(",
"cls",
".",
"__name__",
",",
"kmsg",
".",
"entrypoint",
",",
"kmsg",
".",
"uuid",
")",
",",
"extra",
"=",
"dict",
... | Call on received message
:param kser.schemas.Message kmsg: Kafka message
:return: Kafka message
:rtype: kser.schemas.Message | [
"Call",
"on",
"received",
"message"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/controller.py#L88-L101 |
39,832 | cdumay/kser | src/kser/controller.py | Controller.register | def register(cls, name, entrypoint):
""" Register a new entrypoint
:param str name: Key used by messages
:param kser.entry.Entrypoint entrypoint: class to load
:raises ValidationError: Invalid entry
"""
if not issubclass(entrypoint, Entrypoint):
raise Validat... | python | def register(cls, name, entrypoint):
""" Register a new entrypoint
:param str name: Key used by messages
:param kser.entry.Entrypoint entrypoint: class to load
:raises ValidationError: Invalid entry
"""
if not issubclass(entrypoint, Entrypoint):
raise Validat... | [
"def",
"register",
"(",
"cls",
",",
"name",
",",
"entrypoint",
")",
":",
"if",
"not",
"issubclass",
"(",
"entrypoint",
",",
"Entrypoint",
")",
":",
"raise",
"ValidationError",
"(",
"\"Invalid type for entry '{}', MUST implement \"",
"\"kser.entry.Entrypoint\"",
".",
... | Register a new entrypoint
:param str name: Key used by messages
:param kser.entry.Entrypoint entrypoint: class to load
:raises ValidationError: Invalid entry | [
"Register",
"a",
"new",
"entrypoint"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/controller.py#L129-L143 |
39,833 | cdumay/kser | src/kser/controller.py | Controller.run | def run(cls, raw_data):
"""description of run"""
logger.debug("{}.ReceivedFromKafka: {}".format(
cls.__name__, raw_data
))
try:
kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data))
except Exception as exc:
logger.error(
"{}.Impo... | python | def run(cls, raw_data):
"""description of run"""
logger.debug("{}.ReceivedFromKafka: {}".format(
cls.__name__, raw_data
))
try:
kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data))
except Exception as exc:
logger.error(
"{}.Impo... | [
"def",
"run",
"(",
"cls",
",",
"raw_data",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}.ReceivedFromKafka: {}\"",
".",
"format",
"(",
"cls",
".",
"__name__",
",",
"raw_data",
")",
")",
"try",
":",
"kmsg",
"=",
"cls",
".",
"_onmessage",
"(",
"cls",
".",... | description of run | [
"description",
"of",
"run"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/controller.py#L146-L186 |
39,834 | DeVilhena-Paulo/KdQuery | kdquery.py | Tree.deactivate | def deactivate(self, node_id):
"""Deactivate the node identified by node_id.
Deactivates the node corresponding to node_id, which means that
it can never be the output of a nearest_point query.
Note:
The node is not removed from the tree, its data is steel available.
... | python | def deactivate(self, node_id):
"""Deactivate the node identified by node_id.
Deactivates the node corresponding to node_id, which means that
it can never be the output of a nearest_point query.
Note:
The node is not removed from the tree, its data is steel available.
... | [
"def",
"deactivate",
"(",
"self",
",",
"node_id",
")",
":",
"node",
"=",
"self",
".",
"node_list",
"[",
"node_id",
"]",
"self",
".",
"node_list",
"[",
"node_id",
"]",
"=",
"node",
".",
"_replace",
"(",
"active",
"=",
"False",
")"
] | Deactivate the node identified by node_id.
Deactivates the node corresponding to node_id, which means that
it can never be the output of a nearest_point query.
Note:
The node is not removed from the tree, its data is steel available.
Args:
node_id (int): The no... | [
"Deactivate",
"the",
"node",
"identified",
"by",
"node_id",
"."
] | 76e3791e25b2db2168c1007fe1b92c3f8ec20005 | https://github.com/DeVilhena-Paulo/KdQuery/blob/76e3791e25b2db2168c1007fe1b92c3f8ec20005/kdquery.py#L83-L98 |
39,835 | DeVilhena-Paulo/KdQuery | kdquery.py | Tree.insert | def insert(self, point, data=None):
"""Insert a new node in the tree.
Args:
point (:obj:`tuple` of float or int): Stores the position of the
node.
data (:obj, optional): The information stored by the node.
Returns:
int: The identifier of the ... | python | def insert(self, point, data=None):
"""Insert a new node in the tree.
Args:
point (:obj:`tuple` of float or int): Stores the position of the
node.
data (:obj, optional): The information stored by the node.
Returns:
int: The identifier of the ... | [
"def",
"insert",
"(",
"self",
",",
"point",
",",
"data",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"point",
")",
"==",
"self",
".",
"k",
"if",
"self",
".",
"size",
"==",
"0",
":",
"if",
"self",
".",
"region",
"is",
"None",
":",
"self",
".",
... | Insert a new node in the tree.
Args:
point (:obj:`tuple` of float or int): Stores the position of the
node.
data (:obj, optional): The information stored by the node.
Returns:
int: The identifier of the new node.
Example:
>>> tre... | [
"Insert",
"a",
"new",
"node",
"in",
"the",
"tree",
"."
] | 76e3791e25b2db2168c1007fe1b92c3f8ec20005 | https://github.com/DeVilhena-Paulo/KdQuery/blob/76e3791e25b2db2168c1007fe1b92c3f8ec20005/kdquery.py#L100-L156 |
39,836 | mozilla/rna | rna/admin.py | ReleaseAdmin.set_to_public | def set_to_public(self, request, queryset):
""" Set one or several releases to public """
queryset.update(is_public=True, modified=now()) | python | def set_to_public(self, request, queryset):
""" Set one or several releases to public """
queryset.update(is_public=True, modified=now()) | [
"def",
"set_to_public",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"queryset",
".",
"update",
"(",
"is_public",
"=",
"True",
",",
"modified",
"=",
"now",
"(",
")",
")"
] | Set one or several releases to public | [
"Set",
"one",
"or",
"several",
"releases",
"to",
"public"
] | c1d3931f577dc9c54997f876d36bc0b44dc225ea | https://github.com/mozilla/rna/blob/c1d3931f577dc9c54997f876d36bc0b44dc225ea/rna/admin.py#L102-L104 |
39,837 | cdumay/kser | src/kser/schemas.py | Message.loads | def loads(cls, json_data):
"""description of load"""
try:
return cls(**cls.MARSHMALLOW_SCHEMA.loads(json_data))
except marshmallow.exceptions.ValidationError as exc:
raise ValidationError("Failed to load message", extra=exc.args[0]) | python | def loads(cls, json_data):
"""description of load"""
try:
return cls(**cls.MARSHMALLOW_SCHEMA.loads(json_data))
except marshmallow.exceptions.ValidationError as exc:
raise ValidationError("Failed to load message", extra=exc.args[0]) | [
"def",
"loads",
"(",
"cls",
",",
"json_data",
")",
":",
"try",
":",
"return",
"cls",
"(",
"*",
"*",
"cls",
".",
"MARSHMALLOW_SCHEMA",
".",
"loads",
"(",
"json_data",
")",
")",
"except",
"marshmallow",
".",
"exceptions",
".",
"ValidationError",
"as",
"exc... | description of load | [
"description",
"of",
"load"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/schemas.py#L50-L55 |
39,838 | wuher/devil | devil/datamapper.py | DataMapper.format | def format(self, response):
""" Format the data.
In derived classes, it is usually better idea to override
``_format_data()`` than this method.
:param response: devil's ``Response`` object or the data
itself. May also be ``None``.
:return: django's ``Ht... | python | def format(self, response):
""" Format the data.
In derived classes, it is usually better idea to override
``_format_data()`` than this method.
:param response: devil's ``Response`` object or the data
itself. May also be ``None``.
:return: django's ``Ht... | [
"def",
"format",
"(",
"self",
",",
"response",
")",
":",
"res",
"=",
"self",
".",
"_prepare_response",
"(",
"response",
")",
"res",
".",
"content",
"=",
"self",
".",
"_format_data",
"(",
"res",
".",
"content",
",",
"self",
".",
"charset",
")",
"return"... | Format the data.
In derived classes, it is usually better idea to override
``_format_data()`` than this method.
:param response: devil's ``Response`` object or the data
itself. May also be ``None``.
:return: django's ``HttpResponse``
todo: this shouldn... | [
"Format",
"the",
"data",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L26-L42 |
39,839 | wuher/devil | devil/datamapper.py | DataMapper.parse | def parse(self, data, charset=None):
""" Parse the data.
It is usually a better idea to override ``_parse_data()`` than
this method in derived classes.
:param charset: the charset of the data. Uses datamapper's
default (``self.charset``) if not given.
:returns:
... | python | def parse(self, data, charset=None):
""" Parse the data.
It is usually a better idea to override ``_parse_data()`` than
this method in derived classes.
:param charset: the charset of the data. Uses datamapper's
default (``self.charset``) if not given.
:returns:
... | [
"def",
"parse",
"(",
"self",
",",
"data",
",",
"charset",
"=",
"None",
")",
":",
"charset",
"=",
"charset",
"or",
"self",
".",
"charset",
"return",
"self",
".",
"_parse_data",
"(",
"data",
",",
"charset",
")"
] | Parse the data.
It is usually a better idea to override ``_parse_data()`` than
this method in derived classes.
:param charset: the charset of the data. Uses datamapper's
default (``self.charset``) if not given.
:returns: | [
"Parse",
"the",
"data",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L44-L56 |
39,840 | wuher/devil | devil/datamapper.py | DataMapper._decode_data | def _decode_data(self, data, charset):
""" Decode string data.
:returns: unicode string
"""
try:
return smart_unicode(data, charset)
except UnicodeDecodeError:
raise errors.BadRequest('wrong charset') | python | def _decode_data(self, data, charset):
""" Decode string data.
:returns: unicode string
"""
try:
return smart_unicode(data, charset)
except UnicodeDecodeError:
raise errors.BadRequest('wrong charset') | [
"def",
"_decode_data",
"(",
"self",
",",
"data",
",",
"charset",
")",
":",
"try",
":",
"return",
"smart_unicode",
"(",
"data",
",",
"charset",
")",
"except",
"UnicodeDecodeError",
":",
"raise",
"errors",
".",
"BadRequest",
"(",
"'wrong charset'",
")"
] | Decode string data.
:returns: unicode string | [
"Decode",
"string",
"data",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L58-L67 |
39,841 | wuher/devil | devil/datamapper.py | DataMapper._parse_data | def _parse_data(self, data, charset):
""" Parse the data
:param data: the data (may be None)
"""
return self._decode_data(data, charset) if data else u'' | python | def _parse_data(self, data, charset):
""" Parse the data
:param data: the data (may be None)
"""
return self._decode_data(data, charset) if data else u'' | [
"def",
"_parse_data",
"(",
"self",
",",
"data",
",",
"charset",
")",
":",
"return",
"self",
".",
"_decode_data",
"(",
"data",
",",
"charset",
")",
"if",
"data",
"else",
"u''"
] | Parse the data
:param data: the data (may be None) | [
"Parse",
"the",
"data"
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L81-L87 |
39,842 | wuher/devil | devil/datamapper.py | DataMapper._finalize_response | def _finalize_response(self, response):
""" Convert the ``Response`` object into django's ``HttpResponse``
:return: django's ``HttpResponse``
"""
res = HttpResponse(content=response.content,
content_type=self._get_content_type())
# status_code is set ... | python | def _finalize_response(self, response):
""" Convert the ``Response`` object into django's ``HttpResponse``
:return: django's ``HttpResponse``
"""
res = HttpResponse(content=response.content,
content_type=self._get_content_type())
# status_code is set ... | [
"def",
"_finalize_response",
"(",
"self",
",",
"response",
")",
":",
"res",
"=",
"HttpResponse",
"(",
"content",
"=",
"response",
".",
"content",
",",
"content_type",
"=",
"self",
".",
"_get_content_type",
"(",
")",
")",
"# status_code is set separately to allow z... | Convert the ``Response`` object into django's ``HttpResponse``
:return: django's ``HttpResponse`` | [
"Convert",
"the",
"Response",
"object",
"into",
"django",
"s",
"HttpResponse"
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L102-L112 |
39,843 | wuher/devil | devil/datamapper.py | DataMapperManager.register_mapper | def register_mapper(self, mapper, content_type, shortname=None):
""" Register new mapper.
:param mapper: mapper object needs to implement ``parse()`` and
``format()`` functions.
"""
self._check_mapper(mapper)
cont_type_names = self._get_content_type_names(content_type, ... | python | def register_mapper(self, mapper, content_type, shortname=None):
""" Register new mapper.
:param mapper: mapper object needs to implement ``parse()`` and
``format()`` functions.
"""
self._check_mapper(mapper)
cont_type_names = self._get_content_type_names(content_type, ... | [
"def",
"register_mapper",
"(",
"self",
",",
"mapper",
",",
"content_type",
",",
"shortname",
"=",
"None",
")",
":",
"self",
".",
"_check_mapper",
"(",
"mapper",
")",
"cont_type_names",
"=",
"self",
".",
"_get_content_type_names",
"(",
"content_type",
",",
"sho... | Register new mapper.
:param mapper: mapper object needs to implement ``parse()`` and
``format()`` functions. | [
"Register",
"new",
"mapper",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L147-L156 |
39,844 | wuher/devil | devil/datamapper.py | DataMapperManager.select_formatter | def select_formatter(self, request, resource):
""" Select appropriate formatter based on the request.
:param request: the HTTP request
:param resource: the invoked resource
"""
# 1. get from resource
if resource.mapper:
return resource.mapper
# 2. ge... | python | def select_formatter(self, request, resource):
""" Select appropriate formatter based on the request.
:param request: the HTTP request
:param resource: the invoked resource
"""
# 1. get from resource
if resource.mapper:
return resource.mapper
# 2. ge... | [
"def",
"select_formatter",
"(",
"self",
",",
"request",
",",
"resource",
")",
":",
"# 1. get from resource",
"if",
"resource",
".",
"mapper",
":",
"return",
"resource",
".",
"mapper",
"# 2. get from url",
"mapper_name",
"=",
"self",
".",
"_get_name_from_url",
"(",... | Select appropriate formatter based on the request.
:param request: the HTTP request
:param resource: the invoked resource | [
"Select",
"appropriate",
"formatter",
"based",
"on",
"the",
"request",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L158-L180 |
39,845 | wuher/devil | devil/datamapper.py | DataMapperManager.select_parser | def select_parser(self, request, resource):
""" Select appropriate parser based on the request.
:param request: the HTTP request
:param resource: the invoked resource
"""
# 1. get from resource
if resource.mapper:
return resource.mapper
# 2. get from... | python | def select_parser(self, request, resource):
""" Select appropriate parser based on the request.
:param request: the HTTP request
:param resource: the invoked resource
"""
# 1. get from resource
if resource.mapper:
return resource.mapper
# 2. get from... | [
"def",
"select_parser",
"(",
"self",
",",
"request",
",",
"resource",
")",
":",
"# 1. get from resource",
"if",
"resource",
".",
"mapper",
":",
"return",
"resource",
".",
"mapper",
"# 2. get from content type",
"mapper_name",
"=",
"self",
".",
"_get_name_from_conten... | Select appropriate parser based on the request.
:param request: the HTTP request
:param resource: the invoked resource | [
"Select",
"appropriate",
"parser",
"based",
"on",
"the",
"request",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L182-L204 |
39,846 | wuher/devil | devil/datamapper.py | DataMapperManager.get_mapper_by_content_type | def get_mapper_by_content_type(self, content_type):
""" Returs mapper based on the content type. """
content_type = util.strip_charset(content_type)
return self._get_mapper(content_type) | python | def get_mapper_by_content_type(self, content_type):
""" Returs mapper based on the content type. """
content_type = util.strip_charset(content_type)
return self._get_mapper(content_type) | [
"def",
"get_mapper_by_content_type",
"(",
"self",
",",
"content_type",
")",
":",
"content_type",
"=",
"util",
".",
"strip_charset",
"(",
"content_type",
")",
"return",
"self",
".",
"_get_mapper",
"(",
"content_type",
")"
] | Returs mapper based on the content type. | [
"Returs",
"mapper",
"based",
"on",
"the",
"content",
"type",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L206-L210 |
39,847 | wuher/devil | devil/datamapper.py | DataMapperManager._get_mapper | def _get_mapper(self, mapper_name):
""" Return the mapper based on the given name.
:returns: the mapper based on the given ``mapper_name``
:raises: NotAcceptable if we don't support the requested format.
"""
if mapper_name in self._datamappers:
# mapper found
... | python | def _get_mapper(self, mapper_name):
""" Return the mapper based on the given name.
:returns: the mapper based on the given ``mapper_name``
:raises: NotAcceptable if we don't support the requested format.
"""
if mapper_name in self._datamappers:
# mapper found
... | [
"def",
"_get_mapper",
"(",
"self",
",",
"mapper_name",
")",
":",
"if",
"mapper_name",
"in",
"self",
".",
"_datamappers",
":",
"# mapper found",
"return",
"self",
".",
"_datamappers",
"[",
"mapper_name",
"]",
"else",
":",
"# unsupported format",
"return",
"self",... | Return the mapper based on the given name.
:returns: the mapper based on the given ``mapper_name``
:raises: NotAcceptable if we don't support the requested format. | [
"Return",
"the",
"mapper",
"based",
"on",
"the",
"given",
"name",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L232-L244 |
39,848 | wuher/devil | devil/datamapper.py | DataMapperManager._get_name_from_content_type | def _get_name_from_content_type(self, request):
""" Get name from Content-Type header """
content_type = request.META.get('CONTENT_TYPE', None)
if content_type:
# remove the possible charset-encoding info
return util.strip_charset(content_type)
return None | python | def _get_name_from_content_type(self, request):
""" Get name from Content-Type header """
content_type = request.META.get('CONTENT_TYPE', None)
if content_type:
# remove the possible charset-encoding info
return util.strip_charset(content_type)
return None | [
"def",
"_get_name_from_content_type",
"(",
"self",
",",
"request",
")",
":",
"content_type",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'CONTENT_TYPE'",
",",
"None",
")",
"if",
"content_type",
":",
"# remove the possible charset-encoding info",
"return",
"util",... | Get name from Content-Type header | [
"Get",
"name",
"from",
"Content",
"-",
"Type",
"header"
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L246-L253 |
39,849 | wuher/devil | devil/datamapper.py | DataMapperManager._get_name_from_accept | def _get_name_from_accept(self, request):
""" Process the Accept HTTP header.
Find the most suitable mapper that the client wants and we support.
:returns: the preferred mapper based on the accept header or ``None``.
"""
accepts = util.parse_accept_header(request.META.get("HTT... | python | def _get_name_from_accept(self, request):
""" Process the Accept HTTP header.
Find the most suitable mapper that the client wants and we support.
:returns: the preferred mapper based on the accept header or ``None``.
"""
accepts = util.parse_accept_header(request.META.get("HTT... | [
"def",
"_get_name_from_accept",
"(",
"self",
",",
"request",
")",
":",
"accepts",
"=",
"util",
".",
"parse_accept_header",
"(",
"request",
".",
"META",
".",
"get",
"(",
"\"HTTP_ACCEPT\"",
",",
"\"\"",
")",
")",
"if",
"not",
"accepts",
":",
"return",
"None"... | Process the Accept HTTP header.
Find the most suitable mapper that the client wants and we support.
:returns: the preferred mapper based on the accept header or ``None``. | [
"Process",
"the",
"Accept",
"HTTP",
"header",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L255-L270 |
39,850 | wuher/devil | devil/datamapper.py | DataMapperManager._get_name_from_url | def _get_name_from_url(self, request):
""" Determine short name for the mapper based on the URL.
Short name can be either in query string (e.g. ?format=json)
or as an extension to the URL (e.g. myresource.json).
:returns: short name of the mapper or ``None`` if not found.
"""
... | python | def _get_name_from_url(self, request):
""" Determine short name for the mapper based on the URL.
Short name can be either in query string (e.g. ?format=json)
or as an extension to the URL (e.g. myresource.json).
:returns: short name of the mapper or ``None`` if not found.
"""
... | [
"def",
"_get_name_from_url",
"(",
"self",
",",
"request",
")",
":",
"format",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'format'",
",",
"None",
")",
"if",
"not",
"format",
":",
"match",
"=",
"self",
".",
"_format_query_pattern",
".",
"match",
"(",
... | Determine short name for the mapper based on the URL.
Short name can be either in query string (e.g. ?format=json)
or as an extension to the URL (e.g. myresource.json).
:returns: short name of the mapper or ``None`` if not found. | [
"Determine",
"short",
"name",
"for",
"the",
"mapper",
"based",
"on",
"the",
"URL",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L272-L286 |
39,851 | wuher/devil | devil/datamapper.py | DataMapperManager._check_mapper | def _check_mapper(self, mapper):
""" Check that the mapper has valid signature. """
if not hasattr(mapper, 'parse') or not callable(mapper.parse):
raise ValueError('mapper must implement parse()')
if not hasattr(mapper, 'format') or not callable(mapper.format):
raise Valu... | python | def _check_mapper(self, mapper):
""" Check that the mapper has valid signature. """
if not hasattr(mapper, 'parse') or not callable(mapper.parse):
raise ValueError('mapper must implement parse()')
if not hasattr(mapper, 'format') or not callable(mapper.format):
raise Valu... | [
"def",
"_check_mapper",
"(",
"self",
",",
"mapper",
")",
":",
"if",
"not",
"hasattr",
"(",
"mapper",
",",
"'parse'",
")",
"or",
"not",
"callable",
"(",
"mapper",
".",
"parse",
")",
":",
"raise",
"ValueError",
"(",
"'mapper must implement parse()'",
")",
"i... | Check that the mapper has valid signature. | [
"Check",
"that",
"the",
"mapper",
"has",
"valid",
"signature",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/datamapper.py#L305-L310 |
39,852 | TissueMAPS/TmDeploy | elasticluster/elasticluster/providers/ansible_provider.py | AnsibleSetupProvider.cleanup | def cleanup(self, cluster):
"""Deletes the inventory file used last recently used.
:param cluster: cluster to clear up inventory file for
:type cluster: :py:class:`elasticluster.cluster.Cluster`
"""
if self._storage_path and os.path.exists(self._storage_path):
fname ... | python | def cleanup(self, cluster):
"""Deletes the inventory file used last recently used.
:param cluster: cluster to clear up inventory file for
:type cluster: :py:class:`elasticluster.cluster.Cluster`
"""
if self._storage_path and os.path.exists(self._storage_path):
fname ... | [
"def",
"cleanup",
"(",
"self",
",",
"cluster",
")",
":",
"if",
"self",
".",
"_storage_path",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_storage_path",
")",
":",
"fname",
"=",
"'%s.%s'",
"%",
"(",
"AnsibleSetupProvider",
".",
"inventory_... | Deletes the inventory file used last recently used.
:param cluster: cluster to clear up inventory file for
:type cluster: :py:class:`elasticluster.cluster.Cluster` | [
"Deletes",
"the",
"inventory",
"file",
"used",
"last",
"recently",
"used",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/providers/ansible_provider.py#L348-L368 |
39,853 | tradenity/python-sdk | tradenity/resources/tax_rate.py | TaxRate.based_on | def based_on(self, based_on):
"""Sets the based_on of this TaxRate.
:param based_on: The based_on of this TaxRate.
:type: str
"""
allowed_values = ["shippingAddress", "billingAddress"]
if based_on is not None and based_on not in allowed_values:
raise ValueEr... | python | def based_on(self, based_on):
"""Sets the based_on of this TaxRate.
:param based_on: The based_on of this TaxRate.
:type: str
"""
allowed_values = ["shippingAddress", "billingAddress"]
if based_on is not None and based_on not in allowed_values:
raise ValueEr... | [
"def",
"based_on",
"(",
"self",
",",
"based_on",
")",
":",
"allowed_values",
"=",
"[",
"\"shippingAddress\"",
",",
"\"billingAddress\"",
"]",
"if",
"based_on",
"is",
"not",
"None",
"and",
"based_on",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
"... | Sets the based_on of this TaxRate.
:param based_on: The based_on of this TaxRate.
:type: str | [
"Sets",
"the",
"based_on",
"of",
"this",
"TaxRate",
"."
] | d13fbe23f4d6ff22554c6d8d2deaf209371adaf1 | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/tax_rate.py#L339-L353 |
39,854 | claymcleod/celcius | lib/celcius/tasks.py | build_append_file_task | def build_append_file_task(urllocation, filelocation):
"""Build a task to watch a specific remote url and
append that data to the file. This method should be used
when you would like to keep all of the information stored
on the local machine, but also append the new information
found at the url.
For instance, if t... | python | def build_append_file_task(urllocation, filelocation):
"""Build a task to watch a specific remote url and
append that data to the file. This method should be used
when you would like to keep all of the information stored
on the local machine, but also append the new information
found at the url.
For instance, if t... | [
"def",
"build_append_file_task",
"(",
"urllocation",
",",
"filelocation",
")",
":",
"config",
"=",
"file_utils",
".",
"get_celcius_config",
"(",
")",
"basename",
"=",
"filelocation",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"tmp_filelocation",
"=",
... | Build a task to watch a specific remote url and
append that data to the file. This method should be used
when you would like to keep all of the information stored
on the local machine, but also append the new information
found at the url.
For instance, if the local file is:
```
foo
```
And the remote file is:
```
b... | [
"Build",
"a",
"task",
"to",
"watch",
"a",
"specific",
"remote",
"url",
"and",
"append",
"that",
"data",
"to",
"the",
"file",
".",
"This",
"method",
"should",
"be",
"used",
"when",
"you",
"would",
"like",
"to",
"keep",
"all",
"of",
"the",
"information",
... | e46a3c1ba112af9de23360d1455ab1e037a38ea1 | https://github.com/claymcleod/celcius/blob/e46a3c1ba112af9de23360d1455ab1e037a38ea1/lib/celcius/tasks.py#L11-L56 |
39,855 | volfpeter/graphscraper | src/graphscraper/igraphwrapper.py | IGraphWrapper._create_memory_database_interface | def _create_memory_database_interface(self) -> GraphDatabaseInterface:
"""
Creates and returns the in-memory database interface the graph will use.
"""
Base = declarative_base()
engine = sqlalchemy.create_engine("sqlite://", poolclass=StaticPool)
Session = sessionmaker(bi... | python | def _create_memory_database_interface(self) -> GraphDatabaseInterface:
"""
Creates and returns the in-memory database interface the graph will use.
"""
Base = declarative_base()
engine = sqlalchemy.create_engine("sqlite://", poolclass=StaticPool)
Session = sessionmaker(bi... | [
"def",
"_create_memory_database_interface",
"(",
"self",
")",
"->",
"GraphDatabaseInterface",
":",
"Base",
"=",
"declarative_base",
"(",
")",
"engine",
"=",
"sqlalchemy",
".",
"create_engine",
"(",
"\"sqlite://\"",
",",
"poolclass",
"=",
"StaticPool",
")",
"Session"... | Creates and returns the in-memory database interface the graph will use. | [
"Creates",
"and",
"returns",
"the",
"in",
"-",
"memory",
"database",
"interface",
"the",
"graph",
"will",
"use",
"."
] | 11d407509956a282ee25190ed6491a162fc0fe7f | https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/igraphwrapper.py#L107-L122 |
39,856 | volfpeter/graphscraper | src/graphscraper/igraphwrapper.py | IGraphNodeList._create_node | def _create_node(self, index: int, name: str, external_id: Optional[str] = None) -> IGraphNode:
"""
Returns a new `IGraphNode` instance with the given index and name.
Arguments:
index (int): The index of the node to create.
name (str): The name of the node to create.
... | python | def _create_node(self, index: int, name: str, external_id: Optional[str] = None) -> IGraphNode:
"""
Returns a new `IGraphNode` instance with the given index and name.
Arguments:
index (int): The index of the node to create.
name (str): The name of the node to create.
... | [
"def",
"_create_node",
"(",
"self",
",",
"index",
":",
"int",
",",
"name",
":",
"str",
",",
"external_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"IGraphNode",
":",
"return",
"IGraphNode",
"(",
"graph",
"=",
"self",
".",
"_graph",
... | Returns a new `IGraphNode` instance with the given index and name.
Arguments:
index (int): The index of the node to create.
name (str): The name of the node to create.
external_id (Optional[str]): The external ID of the node. | [
"Returns",
"a",
"new",
"IGraphNode",
"instance",
"with",
"the",
"given",
"index",
"and",
"name",
"."
] | 11d407509956a282ee25190ed6491a162fc0fe7f | https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/igraphwrapper.py#L218-L227 |
39,857 | orbeckst/RecSQL | recsql/rest_table.py | Table2array.parse | def parse(self):
"""Parse the table data string into records."""
self.parse_fields()
records = []
for line in self.t['data'].split('\n'):
if EMPTY_ROW.match(line):
continue
row = [self.autoconvert(line[start_field:end_field+1])
... | python | def parse(self):
"""Parse the table data string into records."""
self.parse_fields()
records = []
for line in self.t['data'].split('\n'):
if EMPTY_ROW.match(line):
continue
row = [self.autoconvert(line[start_field:end_field+1])
... | [
"def",
"parse",
"(",
"self",
")",
":",
"self",
".",
"parse_fields",
"(",
")",
"records",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"t",
"[",
"'data'",
"]",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"EMPTY_ROW",
".",
"match",
"(",
"line",... | Parse the table data string into records. | [
"Parse",
"the",
"table",
"data",
"string",
"into",
"records",
"."
] | 6acbf821022361719391697c9c2f0822f9f8022a | https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/rest_table.py#L191-L202 |
39,858 | orbeckst/RecSQL | recsql/rest_table.py | Table2array.parse_fields | def parse_fields(self):
"""Determine the start and end columns and names of the fields."""
rule = self.t['toprule'].rstrip() # keep leading space for correct columns!!
if not (rule == self.t['midrule'].rstrip() and rule == self.t['botrule'].rstrip()):
raise ParseError("Table rules ... | python | def parse_fields(self):
"""Determine the start and end columns and names of the fields."""
rule = self.t['toprule'].rstrip() # keep leading space for correct columns!!
if not (rule == self.t['midrule'].rstrip() and rule == self.t['botrule'].rstrip()):
raise ParseError("Table rules ... | [
"def",
"parse_fields",
"(",
"self",
")",
":",
"rule",
"=",
"self",
".",
"t",
"[",
"'toprule'",
"]",
".",
"rstrip",
"(",
")",
"# keep leading space for correct columns!!",
"if",
"not",
"(",
"rule",
"==",
"self",
".",
"t",
"[",
"'midrule'",
"]",
".",
"rstr... | Determine the start and end columns and names of the fields. | [
"Determine",
"the",
"start",
"and",
"end",
"columns",
"and",
"names",
"of",
"the",
"fields",
"."
] | 6acbf821022361719391697c9c2f0822f9f8022a | https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/rest_table.py#L234-L262 |
39,859 | inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/checkers.py | check_arguments_compatibility | def check_arguments_compatibility(the_callable, argd):
"""
Check if calling the_callable with the given arguments would be correct
or not.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'})
... | python | def check_arguments_compatibility(the_callable, argd):
"""
Check if calling the_callable with the given arguments would be correct
or not.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'})
... | [
"def",
"check_arguments_compatibility",
"(",
"the_callable",
",",
"argd",
")",
":",
"if",
"not",
"argd",
":",
"argd",
"=",
"{",
"}",
"args",
",",
"dummy",
",",
"varkw",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"the_callable",
")",
"tmp_args... | Check if calling the_callable with the given arguments would be correct
or not.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'})
... except ValueError as err: print 'failed'
... else: print... | [
"Check",
"if",
"calling",
"the_callable",
"with",
"the",
"given",
"arguments",
"would",
"be",
"correct",
"or",
"not",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/checkers.py#L176-L242 |
39,860 | henocdz/workon | workon/script.py | WorkOn._print | def _print(self, text, color=None, **kwargs):
"""print text with given color to terminal
"""
COLORS = {
'red': '\033[91m{}\033[00m',
'green': '\033[92m{}\033[00m',
'yellow': '\033[93m{}\033[00m',
'cyan': '\033[96m{}\033[00m'
}
_ = C... | python | def _print(self, text, color=None, **kwargs):
"""print text with given color to terminal
"""
COLORS = {
'red': '\033[91m{}\033[00m',
'green': '\033[92m{}\033[00m',
'yellow': '\033[93m{}\033[00m',
'cyan': '\033[96m{}\033[00m'
}
_ = C... | [
"def",
"_print",
"(",
"self",
",",
"text",
",",
"color",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"COLORS",
"=",
"{",
"'red'",
":",
"'\\033[91m{}\\033[00m'",
",",
"'green'",
":",
"'\\033[92m{}\\033[00m'",
",",
"'yellow'",
":",
"'\\033[93m{}\\033[00m'"... | print text with given color to terminal | [
"print",
"text",
"with",
"given",
"color",
"to",
"terminal"
] | 46f1f6dc4ea95d8efd10adf93a06737237a6874d | https://github.com/henocdz/workon/blob/46f1f6dc4ea95d8efd10adf93a06737237a6874d/workon/script.py#L22-L32 |
39,861 | henocdz/workon | workon/script.py | WorkOn._is_unique | def _is_unique(self, name, path):
"""verify if there is a project with given name or path
on the database
"""
project = None
try:
project = Project.select().where(
(Project.name == name) |
(Project.path == path)
)[0]
... | python | def _is_unique(self, name, path):
"""verify if there is a project with given name or path
on the database
"""
project = None
try:
project = Project.select().where(
(Project.name == name) |
(Project.path == path)
)[0]
... | [
"def",
"_is_unique",
"(",
"self",
",",
"name",
",",
"path",
")",
":",
"project",
"=",
"None",
"try",
":",
"project",
"=",
"Project",
".",
"select",
"(",
")",
".",
"where",
"(",
"(",
"Project",
".",
"name",
"==",
"name",
")",
"|",
"(",
"Project",
... | verify if there is a project with given name or path
on the database | [
"verify",
"if",
"there",
"is",
"a",
"project",
"with",
"given",
"name",
"or",
"path",
"on",
"the",
"database"
] | 46f1f6dc4ea95d8efd10adf93a06737237a6874d | https://github.com/henocdz/workon/blob/46f1f6dc4ea95d8efd10adf93a06737237a6874d/workon/script.py#L34-L47 |
39,862 | henocdz/workon | workon/script.py | WorkOn.add | def add(self, name, path=None, **kwargs):
"""add new project with given name and path to database
if the path is not given, current working directory will be taken
...as default
"""
path = path or kwargs.pop('default_path', None)
if not self._path_is_valid(path):
... | python | def add(self, name, path=None, **kwargs):
"""add new project with given name and path to database
if the path is not given, current working directory will be taken
...as default
"""
path = path or kwargs.pop('default_path', None)
if not self._path_is_valid(path):
... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"path",
"or",
"kwargs",
".",
"pop",
"(",
"'default_path'",
",",
"None",
")",
"if",
"not",
"self",
".",
"_path_is_valid",
"(",
"path",
... | add new project with given name and path to database
if the path is not given, current working directory will be taken
...as default | [
"add",
"new",
"project",
"with",
"given",
"name",
"and",
"path",
"to",
"database",
"if",
"the",
"path",
"is",
"not",
"given",
"current",
"working",
"directory",
"will",
"be",
"taken",
"...",
"as",
"default"
] | 46f1f6dc4ea95d8efd10adf93a06737237a6874d | https://github.com/henocdz/workon/blob/46f1f6dc4ea95d8efd10adf93a06737237a6874d/workon/script.py#L76-L95 |
39,863 | henocdz/workon | workon/script.py | WorkOn.list | def list(self, **kwargs):
"""displays all projects on database
"""
projects = Project.select().order_by(Project.name)
if len(projects) == 0:
self._print('No projects available', 'yellow')
return
for project in projects:
project_repr = self._PR... | python | def list(self, **kwargs):
"""displays all projects on database
"""
projects = Project.select().order_by(Project.name)
if len(projects) == 0:
self._print('No projects available', 'yellow')
return
for project in projects:
project_repr = self._PR... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"projects",
"=",
"Project",
".",
"select",
"(",
")",
".",
"order_by",
"(",
"Project",
".",
"name",
")",
"if",
"len",
"(",
"projects",
")",
"==",
"0",
":",
"self",
".",
"_print",
"(",
... | displays all projects on database | [
"displays",
"all",
"projects",
"on",
"database"
] | 46f1f6dc4ea95d8efd10adf93a06737237a6874d | https://github.com/henocdz/workon/blob/46f1f6dc4ea95d8efd10adf93a06737237a6874d/workon/script.py#L97-L108 |
39,864 | honzajavorek/tipi | tipi/html.py | HTMLString.parent_tags | def parent_tags(self):
"""Provides tags of all parent HTML elements."""
tags = set()
for addr in self._addresses:
if addr.attr == 'text':
tags.add(addr.element.tag)
tags.update(el.tag for el in addr.element.iterancestors())
tags.discard(HTMLFragm... | python | def parent_tags(self):
"""Provides tags of all parent HTML elements."""
tags = set()
for addr in self._addresses:
if addr.attr == 'text':
tags.add(addr.element.tag)
tags.update(el.tag for el in addr.element.iterancestors())
tags.discard(HTMLFragm... | [
"def",
"parent_tags",
"(",
"self",
")",
":",
"tags",
"=",
"set",
"(",
")",
"for",
"addr",
"in",
"self",
".",
"_addresses",
":",
"if",
"addr",
".",
"attr",
"==",
"'text'",
":",
"tags",
".",
"add",
"(",
"addr",
".",
"element",
".",
"tag",
")",
"tag... | Provides tags of all parent HTML elements. | [
"Provides",
"tags",
"of",
"all",
"parent",
"HTML",
"elements",
"."
] | cbe51192725608b6fba1244a48610ae231b13e08 | https://github.com/honzajavorek/tipi/blob/cbe51192725608b6fba1244a48610ae231b13e08/tipi/html.py#L39-L49 |
39,865 | honzajavorek/tipi | tipi/html.py | HTMLString.involved_tags | def involved_tags(self):
"""Provides all HTML tags directly involved in this string."""
if len(self._addresses) < 2:
# there can't be a tag boundary if there's only 1 or 0 characters
return frozenset()
# creating 'parent_sets' mapping, where the first item in tuple
... | python | def involved_tags(self):
"""Provides all HTML tags directly involved in this string."""
if len(self._addresses) < 2:
# there can't be a tag boundary if there's only 1 or 0 characters
return frozenset()
# creating 'parent_sets' mapping, where the first item in tuple
... | [
"def",
"involved_tags",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_addresses",
")",
"<",
"2",
":",
"# there can't be a tag boundary if there's only 1 or 0 characters",
"return",
"frozenset",
"(",
")",
"# creating 'parent_sets' mapping, where the first item in t... | Provides all HTML tags directly involved in this string. | [
"Provides",
"all",
"HTML",
"tags",
"directly",
"involved",
"in",
"this",
"string",
"."
] | cbe51192725608b6fba1244a48610ae231b13e08 | https://github.com/honzajavorek/tipi/blob/cbe51192725608b6fba1244a48610ae231b13e08/tipi/html.py#L52-L100 |
39,866 | honzajavorek/tipi | tipi/html.py | HTMLFragment._parse | def _parse(self, html):
"""Parse given string as HTML and return it's etree representation."""
if self._has_body_re.search(html):
tree = lxml.html.document_fromstring(html).find('.//body')
self.has_body = True
else:
tree = lxml.html.fragment_fromstring(html,
... | python | def _parse(self, html):
"""Parse given string as HTML and return it's etree representation."""
if self._has_body_re.search(html):
tree = lxml.html.document_fromstring(html).find('.//body')
self.has_body = True
else:
tree = lxml.html.fragment_fromstring(html,
... | [
"def",
"_parse",
"(",
"self",
",",
"html",
")",
":",
"if",
"self",
".",
"_has_body_re",
".",
"search",
"(",
"html",
")",
":",
"tree",
"=",
"lxml",
".",
"html",
".",
"document_fromstring",
"(",
"html",
")",
".",
"find",
"(",
"'.//body'",
")",
"self",
... | Parse given string as HTML and return it's etree representation. | [
"Parse",
"given",
"string",
"as",
"HTML",
"and",
"return",
"it",
"s",
"etree",
"representation",
"."
] | cbe51192725608b6fba1244a48610ae231b13e08 | https://github.com/honzajavorek/tipi/blob/cbe51192725608b6fba1244a48610ae231b13e08/tipi/html.py#L133-L149 |
39,867 | honzajavorek/tipi | tipi/html.py | HTMLFragment._iter_texts | def _iter_texts(self, tree):
"""Iterates over texts in given HTML tree."""
skip = (
not isinstance(tree, lxml.html.HtmlElement) # comments, etc.
or tree.tag in self.skipped_tags
)
if not skip:
if tree.text:
yield Text(tree.text, tree, ... | python | def _iter_texts(self, tree):
"""Iterates over texts in given HTML tree."""
skip = (
not isinstance(tree, lxml.html.HtmlElement) # comments, etc.
or tree.tag in self.skipped_tags
)
if not skip:
if tree.text:
yield Text(tree.text, tree, ... | [
"def",
"_iter_texts",
"(",
"self",
",",
"tree",
")",
":",
"skip",
"=",
"(",
"not",
"isinstance",
"(",
"tree",
",",
"lxml",
".",
"html",
".",
"HtmlElement",
")",
"# comments, etc.",
"or",
"tree",
".",
"tag",
"in",
"self",
".",
"skipped_tags",
")",
"if",... | Iterates over texts in given HTML tree. | [
"Iterates",
"over",
"texts",
"in",
"given",
"HTML",
"tree",
"."
] | cbe51192725608b6fba1244a48610ae231b13e08 | https://github.com/honzajavorek/tipi/blob/cbe51192725608b6fba1244a48610ae231b13e08/tipi/html.py#L151-L164 |
39,868 | honzajavorek/tipi | tipi/html.py | HTMLFragment._analyze_tree | def _analyze_tree(self, tree):
"""Analyze given tree and create mapping of indexes to character
addresses.
"""
addresses = []
for text in self._iter_texts(tree):
for i, char in enumerate(text.content):
if char in whitespace:
char = ... | python | def _analyze_tree(self, tree):
"""Analyze given tree and create mapping of indexes to character
addresses.
"""
addresses = []
for text in self._iter_texts(tree):
for i, char in enumerate(text.content):
if char in whitespace:
char = ... | [
"def",
"_analyze_tree",
"(",
"self",
",",
"tree",
")",
":",
"addresses",
"=",
"[",
"]",
"for",
"text",
"in",
"self",
".",
"_iter_texts",
"(",
"tree",
")",
":",
"for",
"i",
",",
"char",
"in",
"enumerate",
"(",
"text",
".",
"content",
")",
":",
"if",... | Analyze given tree and create mapping of indexes to character
addresses. | [
"Analyze",
"given",
"tree",
"and",
"create",
"mapping",
"of",
"indexes",
"to",
"character",
"addresses",
"."
] | cbe51192725608b6fba1244a48610ae231b13e08 | https://github.com/honzajavorek/tipi/blob/cbe51192725608b6fba1244a48610ae231b13e08/tipi/html.py#L166-L183 |
39,869 | honzajavorek/tipi | tipi/html.py | HTMLFragment._validate_index | def _validate_index(self, index):
"""Validates given index, eventually raises errors."""
if isinstance(index, slice):
if index.step and index.step != 1:
raise IndexError('Step is not allowed.')
indexes = (index.start, index.stop)
else:
indexes ... | python | def _validate_index(self, index):
"""Validates given index, eventually raises errors."""
if isinstance(index, slice):
if index.step and index.step != 1:
raise IndexError('Step is not allowed.')
indexes = (index.start, index.stop)
else:
indexes ... | [
"def",
"_validate_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"slice",
")",
":",
"if",
"index",
".",
"step",
"and",
"index",
".",
"step",
"!=",
"1",
":",
"raise",
"IndexError",
"(",
"'Step is not allowed.'",
")",
... | Validates given index, eventually raises errors. | [
"Validates",
"given",
"index",
"eventually",
"raises",
"errors",
"."
] | cbe51192725608b6fba1244a48610ae231b13e08 | https://github.com/honzajavorek/tipi/blob/cbe51192725608b6fba1244a48610ae231b13e08/tipi/html.py#L189-L199 |
39,870 | honzajavorek/tipi | tipi/html.py | HTMLFragment._find_pivot_addr | def _find_pivot_addr(self, index):
"""Inserting by slicing can lead into situation where no addresses are
selected. In that case a pivot address has to be chosen so we know
where to add characters.
"""
if not self.addresses or index.start == 0:
return CharAddress('', ... | python | def _find_pivot_addr(self, index):
"""Inserting by slicing can lead into situation where no addresses are
selected. In that case a pivot address has to be chosen so we know
where to add characters.
"""
if not self.addresses or index.start == 0:
return CharAddress('', ... | [
"def",
"_find_pivot_addr",
"(",
"self",
",",
"index",
")",
":",
"if",
"not",
"self",
".",
"addresses",
"or",
"index",
".",
"start",
"==",
"0",
":",
"return",
"CharAddress",
"(",
"''",
",",
"self",
".",
"tree",
",",
"'text'",
",",
"-",
"1",
")",
"# ... | Inserting by slicing can lead into situation where no addresses are
selected. In that case a pivot address has to be chosen so we know
where to add characters. | [
"Inserting",
"by",
"slicing",
"can",
"lead",
"into",
"situation",
"where",
"no",
"addresses",
"are",
"selected",
".",
"In",
"that",
"case",
"a",
"pivot",
"address",
"has",
"to",
"be",
"chosen",
"so",
"we",
"know",
"where",
"to",
"add",
"characters",
"."
] | cbe51192725608b6fba1244a48610ae231b13e08 | https://github.com/honzajavorek/tipi/blob/cbe51192725608b6fba1244a48610ae231b13e08/tipi/html.py#L210-L219 |
39,871 | blockadeio/analyst_toolbench | blockade/aws/lambda-scripts/Blockade-Add-Indicators.py | check_api_key | def check_api_key(email, api_key):
"""Check the API key of the user."""
table = boto3.resource("dynamodb").Table(os.environ['people'])
user = table.get_item(Key={'email': email})
if not user:
return False
user = user.get("Item")
if api_key != user.get('api_key', None):
return Fal... | python | def check_api_key(email, api_key):
"""Check the API key of the user."""
table = boto3.resource("dynamodb").Table(os.environ['people'])
user = table.get_item(Key={'email': email})
if not user:
return False
user = user.get("Item")
if api_key != user.get('api_key', None):
return Fal... | [
"def",
"check_api_key",
"(",
"email",
",",
"api_key",
")",
":",
"table",
"=",
"boto3",
".",
"resource",
"(",
"\"dynamodb\"",
")",
".",
"Table",
"(",
"os",
".",
"environ",
"[",
"'people'",
"]",
")",
"user",
"=",
"table",
".",
"get_item",
"(",
"Key",
"... | Check the API key of the user. | [
"Check",
"the",
"API",
"key",
"of",
"the",
"user",
"."
] | 159b6f8cf8a91c5ff050f1579636ea90ab269863 | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/aws/lambda-scripts/Blockade-Add-Indicators.py#L12-L21 |
39,872 | honzajavorek/tipi | tipi/repl.py | replace | def replace(html, replacements=None):
"""Performs replacements on given HTML string."""
if not replacements:
return html # no replacements
html = HTMLFragment(html)
for r in replacements:
r.replace(html)
return unicode(html) | python | def replace(html, replacements=None):
"""Performs replacements on given HTML string."""
if not replacements:
return html # no replacements
html = HTMLFragment(html)
for r in replacements:
r.replace(html)
return unicode(html) | [
"def",
"replace",
"(",
"html",
",",
"replacements",
"=",
"None",
")",
":",
"if",
"not",
"replacements",
":",
"return",
"html",
"# no replacements",
"html",
"=",
"HTMLFragment",
"(",
"html",
")",
"for",
"r",
"in",
"replacements",
":",
"r",
".",
"replace",
... | Performs replacements on given HTML string. | [
"Performs",
"replacements",
"on",
"given",
"HTML",
"string",
"."
] | cbe51192725608b6fba1244a48610ae231b13e08 | https://github.com/honzajavorek/tipi/blob/cbe51192725608b6fba1244a48610ae231b13e08/tipi/repl.py#L65-L74 |
39,873 | honzajavorek/tipi | tipi/repl.py | Replacement._is_replacement_allowed | def _is_replacement_allowed(self, s):
"""Tests whether replacement is allowed on given piece of HTML text."""
if any(tag in s.parent_tags for tag in self.skipped_tags):
return False
if any(tag not in self.textflow_tags for tag in s.involved_tags):
return False
ret... | python | def _is_replacement_allowed(self, s):
"""Tests whether replacement is allowed on given piece of HTML text."""
if any(tag in s.parent_tags for tag in self.skipped_tags):
return False
if any(tag not in self.textflow_tags for tag in s.involved_tags):
return False
ret... | [
"def",
"_is_replacement_allowed",
"(",
"self",
",",
"s",
")",
":",
"if",
"any",
"(",
"tag",
"in",
"s",
".",
"parent_tags",
"for",
"tag",
"in",
"self",
".",
"skipped_tags",
")",
":",
"return",
"False",
"if",
"any",
"(",
"tag",
"not",
"in",
"self",
"."... | Tests whether replacement is allowed on given piece of HTML text. | [
"Tests",
"whether",
"replacement",
"is",
"allowed",
"on",
"given",
"piece",
"of",
"HTML",
"text",
"."
] | cbe51192725608b6fba1244a48610ae231b13e08 | https://github.com/honzajavorek/tipi/blob/cbe51192725608b6fba1244a48610ae231b13e08/tipi/repl.py#L28-L34 |
39,874 | honzajavorek/tipi | tipi/repl.py | Replacement.replace | def replace(self, html):
"""Perform replacements on given HTML fragment."""
self.html = html
text = html.text()
positions = []
def perform_replacement(match):
offset = sum(positions)
start, stop = match.start() + offset, match.end() + offset
... | python | def replace(self, html):
"""Perform replacements on given HTML fragment."""
self.html = html
text = html.text()
positions = []
def perform_replacement(match):
offset = sum(positions)
start, stop = match.start() + offset, match.end() + offset
... | [
"def",
"replace",
"(",
"self",
",",
"html",
")",
":",
"self",
".",
"html",
"=",
"html",
"text",
"=",
"html",
".",
"text",
"(",
")",
"positions",
"=",
"[",
"]",
"def",
"perform_replacement",
"(",
"match",
")",
":",
"offset",
"=",
"sum",
"(",
"positi... | Perform replacements on given HTML fragment. | [
"Perform",
"replacements",
"on",
"given",
"HTML",
"fragment",
"."
] | cbe51192725608b6fba1244a48610ae231b13e08 | https://github.com/honzajavorek/tipi/blob/cbe51192725608b6fba1244a48610ae231b13e08/tipi/repl.py#L36-L62 |
39,875 | benoitbryon/rst2rst | rst2rst/utils/__init__.py | read_relative_file | def read_relative_file(filename, relative_to=None):
"""Returns contents of the given file, which path is supposed relative
to this package."""
if relative_to is None:
relative_to = os.path.dirname(__file__)
with open(os.path.join(os.path.dirname(relative_to), filename)) as f:
return f.re... | python | def read_relative_file(filename, relative_to=None):
"""Returns contents of the given file, which path is supposed relative
to this package."""
if relative_to is None:
relative_to = os.path.dirname(__file__)
with open(os.path.join(os.path.dirname(relative_to), filename)) as f:
return f.re... | [
"def",
"read_relative_file",
"(",
"filename",
",",
"relative_to",
"=",
"None",
")",
":",
"if",
"relative_to",
"is",
"None",
":",
"relative_to",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"... | Returns contents of the given file, which path is supposed relative
to this package. | [
"Returns",
"contents",
"of",
"the",
"given",
"file",
"which",
"path",
"is",
"supposed",
"relative",
"to",
"this",
"package",
"."
] | 976eef709aacb1facc8dca87cf7032f01d53adfe | https://github.com/benoitbryon/rst2rst/blob/976eef709aacb1facc8dca87cf7032f01d53adfe/rst2rst/utils/__init__.py#L54-L60 |
39,876 | blockadeio/analyst_toolbench | blockade/libs/events.py | EventsClient.get_events | def get_events(self):
"""Get events from the cloud node."""
to_send = {'limit': 50}
response = self._send_data('POST', 'admin', 'get-events', to_send)
output = {'message': ""}
for event in response['events']:
desc = "Source IP: {ip}\n"
desc += "Datetime: ... | python | def get_events(self):
"""Get events from the cloud node."""
to_send = {'limit': 50}
response = self._send_data('POST', 'admin', 'get-events', to_send)
output = {'message': ""}
for event in response['events']:
desc = "Source IP: {ip}\n"
desc += "Datetime: ... | [
"def",
"get_events",
"(",
"self",
")",
":",
"to_send",
"=",
"{",
"'limit'",
":",
"50",
"}",
"response",
"=",
"self",
".",
"_send_data",
"(",
"'POST'",
",",
"'admin'",
",",
"'get-events'",
",",
"to_send",
")",
"output",
"=",
"{",
"'message'",
":",
"\"\"... | Get events from the cloud node. | [
"Get",
"events",
"from",
"the",
"cloud",
"node",
"."
] | 159b6f8cf8a91c5ff050f1579636ea90ab269863 | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/libs/events.py#L18-L36 |
39,877 | blockadeio/analyst_toolbench | blockade/libs/events.py | EventsClient.flush_events | def flush_events(self):
"""Flush events from the cloud node."""
response = self._send_data('DELETE', 'admin', 'flush-events', {})
if response['success']:
msg = "Events flushed"
else:
msg = "Flushing of events failed"
output = {'message': msg}
ret... | python | def flush_events(self):
"""Flush events from the cloud node."""
response = self._send_data('DELETE', 'admin', 'flush-events', {})
if response['success']:
msg = "Events flushed"
else:
msg = "Flushing of events failed"
output = {'message': msg}
ret... | [
"def",
"flush_events",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_send_data",
"(",
"'DELETE'",
",",
"'admin'",
",",
"'flush-events'",
",",
"{",
"}",
")",
"if",
"response",
"[",
"'success'",
"]",
":",
"msg",
"=",
"\"Events flushed\"",
"else",
... | Flush events from the cloud node. | [
"Flush",
"events",
"from",
"the",
"cloud",
"node",
"."
] | 159b6f8cf8a91c5ff050f1579636ea90ab269863 | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/libs/events.py#L38-L48 |
39,878 | RescueTime/cwmon | src/cwmon/metrics.py | Metric.put | def put(self):
"""Push the info represented by this ``Metric`` to CloudWatch."""
try:
self.cloudwatch.put_metric_data(
Namespace=self.namespace,
MetricData=[{
'MetricName': self.name,
'Value': self.value,... | python | def put(self):
"""Push the info represented by this ``Metric`` to CloudWatch."""
try:
self.cloudwatch.put_metric_data(
Namespace=self.namespace,
MetricData=[{
'MetricName': self.name,
'Value': self.value,... | [
"def",
"put",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"cloudwatch",
".",
"put_metric_data",
"(",
"Namespace",
"=",
"self",
".",
"namespace",
",",
"MetricData",
"=",
"[",
"{",
"'MetricName'",
":",
"self",
".",
"name",
",",
"'Value'",
":",
"self"... | Push the info represented by this ``Metric`` to CloudWatch. | [
"Push",
"the",
"info",
"represented",
"by",
"this",
"Metric",
"to",
"CloudWatch",
"."
] | 1b6713ec700fdebb292099d9f493c8f97ed4ec51 | https://github.com/RescueTime/cwmon/blob/1b6713ec700fdebb292099d9f493c8f97ed4ec51/src/cwmon/metrics.py#L57-L69 |
39,879 | cdumay/kser | src/kser/sequencing/task.py | Task.log | def log(self, message, level=logging.INFO, *args, **kwargs):
""" Send log entry
:param str message: log message
:param int level: `Logging level <https://docs.python.org/3/library/logging.html#levels>`_
:param list args: log record arguments
:param dict kwargs: log record key ar... | python | def log(self, message, level=logging.INFO, *args, **kwargs):
""" Send log entry
:param str message: log message
:param int level: `Logging level <https://docs.python.org/3/library/logging.html#levels>`_
:param list args: log record arguments
:param dict kwargs: log record key ar... | [
"def",
"log",
"(",
"self",
",",
"message",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"\"{}.{}: {}[{}]: {}\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self"... | Send log entry
:param str message: log message
:param int level: `Logging level <https://docs.python.org/3/library/logging.html#levels>`_
:param list args: log record arguments
:param dict kwargs: log record key argument | [
"Send",
"log",
"entry"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/sequencing/task.py#L42-L62 |
39,880 | ONSdigital/sdc-rabbit | sdc/rabbit/publishers.py | Publisher._connect | def _connect(self):
"""
Connect to a RabbitMQ instance
:returns: Boolean corresponding to success of connection
:rtype: bool
"""
logger.info("Connecting to rabbit")
for url in self._urls:
try:
self._connection = pika.BlockingConnectio... | python | def _connect(self):
"""
Connect to a RabbitMQ instance
:returns: Boolean corresponding to success of connection
:rtype: bool
"""
logger.info("Connecting to rabbit")
for url in self._urls:
try:
self._connection = pika.BlockingConnectio... | [
"def",
"_connect",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Connecting to rabbit\"",
")",
"for",
"url",
"in",
"self",
".",
"_urls",
":",
"try",
":",
"self",
".",
"_connection",
"=",
"pika",
".",
"BlockingConnection",
"(",
"pika",
".",
"URLPa... | Connect to a RabbitMQ instance
:returns: Boolean corresponding to success of connection
:rtype: bool | [
"Connect",
"to",
"a",
"RabbitMQ",
"instance"
] | 985adfdb09cf1b263a1f311438baeb42cbcb503a | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/publishers.py#L38-L65 |
39,881 | ONSdigital/sdc-rabbit | sdc/rabbit/publishers.py | Publisher._disconnect | def _disconnect(self):
"""
Cleanly close a RabbitMQ connection.
:returns: None
"""
try:
self._connection.close()
logger.debug("Disconnected from rabbit")
except Exception:
logger.exception("Unable to close connection") | python | def _disconnect(self):
"""
Cleanly close a RabbitMQ connection.
:returns: None
"""
try:
self._connection.close()
logger.debug("Disconnected from rabbit")
except Exception:
logger.exception("Unable to close connection") | [
"def",
"_disconnect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_connection",
".",
"close",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Disconnected from rabbit\"",
")",
"except",
"Exception",
":",
"logger",
".",
"exception",
"(",
"\"Unable to close conne... | Cleanly close a RabbitMQ connection.
:returns: None | [
"Cleanly",
"close",
"a",
"RabbitMQ",
"connection",
"."
] | 985adfdb09cf1b263a1f311438baeb42cbcb503a | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/publishers.py#L67-L78 |
39,882 | ONSdigital/sdc-rabbit | sdc/rabbit/publishers.py | Publisher.publish_message | def publish_message(self, message, content_type=None, headers=None, mandatory=False, immediate=False):
"""
Publish a response message to a RabbitMQ instance.
:param message: Response message
:param content_type: Pika BasicProperties content_type value
:param headers: Message hea... | python | def publish_message(self, message, content_type=None, headers=None, mandatory=False, immediate=False):
"""
Publish a response message to a RabbitMQ instance.
:param message: Response message
:param content_type: Pika BasicProperties content_type value
:param headers: Message hea... | [
"def",
"publish_message",
"(",
"self",
",",
"message",
",",
"content_type",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"mandatory",
"=",
"False",
",",
"immediate",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"Publishing message\"",
")",
"try... | Publish a response message to a RabbitMQ instance.
:param message: Response message
:param content_type: Pika BasicProperties content_type value
:param headers: Message header properties
:param mandatory: The mandatory flag
:param immediate: The immediate flag
:returns:... | [
"Publish",
"a",
"response",
"message",
"to",
"a",
"RabbitMQ",
"instance",
"."
] | 985adfdb09cf1b263a1f311438baeb42cbcb503a | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/publishers.py#L83-L120 |
39,883 | LREN-CHUV/data-tracking | data_tracking/files_recording.py | visit | def visit(folder, provenance_id, step_name, previous_step_id=None, config=None, db_url=None, is_organised=True):
"""Record all files from a folder into the database.
Note:
If a file has been copied from a previous processing step without any transformation, it will be detected and
marked in the DB. The... | python | def visit(folder, provenance_id, step_name, previous_step_id=None, config=None, db_url=None, is_organised=True):
"""Record all files from a folder into the database.
Note:
If a file has been copied from a previous processing step without any transformation, it will be detected and
marked in the DB. The... | [
"def",
"visit",
"(",
"folder",
",",
"provenance_id",
",",
"step_name",
",",
"previous_step_id",
"=",
"None",
",",
"config",
"=",
"None",
",",
"db_url",
"=",
"None",
",",
"is_organised",
"=",
"True",
")",
":",
"config",
"=",
"config",
"if",
"config",
"els... | Record all files from a folder into the database.
Note:
If a file has been copied from a previous processing step without any transformation, it will be detected and
marked in the DB. The type of file will be detected and stored in the DB (NIFTI, DICOM, ...). If a files
(e.g. a DICOM file) contains som... | [
"Record",
"all",
"files",
"from",
"a",
"folder",
"into",
"the",
"database",
"."
] | f645a0d6426e6019c92d5aaf4be225cff2864417 | https://github.com/LREN-CHUV/data-tracking/blob/f645a0d6426e6019c92d5aaf4be225cff2864417/data_tracking/files_recording.py#L33-L121 |
39,884 | sci-bots/dmf-device-ui | dmf_device_ui/plugin.py | DevicePlugin.check_sockets | def check_sockets(self):
'''
Check for new messages on sockets and respond accordingly.
.. versionchanged:: 0.11.3
Update routes table by setting ``df_routes`` property of
:attr:`parent.canvas_slave`.
.. versionchanged:: 0.12
Update ``dynamic_electr... | python | def check_sockets(self):
'''
Check for new messages on sockets and respond accordingly.
.. versionchanged:: 0.11.3
Update routes table by setting ``df_routes`` property of
:attr:`parent.canvas_slave`.
.. versionchanged:: 0.12
Update ``dynamic_electr... | [
"def",
"check_sockets",
"(",
"self",
")",
":",
"try",
":",
"msg_frames",
"=",
"(",
"self",
".",
"command_socket",
".",
"recv_multipart",
"(",
"zmq",
".",
"NOBLOCK",
")",
")",
"except",
"zmq",
".",
"Again",
":",
"pass",
"else",
":",
"self",
".",
"on_com... | Check for new messages on sockets and respond accordingly.
.. versionchanged:: 0.11.3
Update routes table by setting ``df_routes`` property of
:attr:`parent.canvas_slave`.
.. versionchanged:: 0.12
Update ``dynamic_electrode_state_shapes`` layer of
:attr... | [
"Check",
"for",
"new",
"messages",
"on",
"sockets",
"and",
"respond",
"accordingly",
"."
] | 05b480683c9fa43f91ce5a58de2fa90cdf363fc8 | https://github.com/sci-bots/dmf-device-ui/blob/05b480683c9fa43f91ce5a58de2fa90cdf363fc8/dmf_device_ui/plugin.py#L24-L119 |
39,885 | Titan-C/slaveparticles | examples/crystal_field.py | follow_cf | def follow_cf(save, Uspan, target_cf, nup, n_tot=5.0, slsp=None):
"""Calculates the quasiparticle weight in single
site spin hamiltonian under with N degenerate half-filled orbitals """
if slsp == None:
slsp = Spinon(slaves=6, orbitals=3, avg_particles=n_tot,
hopping=[0.5]... | python | def follow_cf(save, Uspan, target_cf, nup, n_tot=5.0, slsp=None):
"""Calculates the quasiparticle weight in single
site spin hamiltonian under with N degenerate half-filled orbitals """
if slsp == None:
slsp = Spinon(slaves=6, orbitals=3, avg_particles=n_tot,
hopping=[0.5]... | [
"def",
"follow_cf",
"(",
"save",
",",
"Uspan",
",",
"target_cf",
",",
"nup",
",",
"n_tot",
"=",
"5.0",
",",
"slsp",
"=",
"None",
")",
":",
"if",
"slsp",
"==",
"None",
":",
"slsp",
"=",
"Spinon",
"(",
"slaves",
"=",
"6",
",",
"orbitals",
"=",
"3",... | Calculates the quasiparticle weight in single
site spin hamiltonian under with N degenerate half-filled orbitals | [
"Calculates",
"the",
"quasiparticle",
"weight",
"in",
"single",
"site",
"spin",
"hamiltonian",
"under",
"with",
"N",
"degenerate",
"half",
"-",
"filled",
"orbitals"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/examples/crystal_field.py#L15-L43 |
39,886 | Titan-C/slaveparticles | examples/crystal_field.py | targetpop | def targetpop(upper_density, coul, target_cf, slsp, n_tot):
"""restriction on finding the right populations that leave the crystal
field same"""
if upper_density < 0.503: return 0.
trypops=population_distri(upper_density, n_tot)
slsp.set_filling(trypops)
slsp.selfconsistency(coul,0)
efm_free... | python | def targetpop(upper_density, coul, target_cf, slsp, n_tot):
"""restriction on finding the right populations that leave the crystal
field same"""
if upper_density < 0.503: return 0.
trypops=population_distri(upper_density, n_tot)
slsp.set_filling(trypops)
slsp.selfconsistency(coul,0)
efm_free... | [
"def",
"targetpop",
"(",
"upper_density",
",",
"coul",
",",
"target_cf",
",",
"slsp",
",",
"n_tot",
")",
":",
"if",
"upper_density",
"<",
"0.503",
":",
"return",
"0.",
"trypops",
"=",
"population_distri",
"(",
"upper_density",
",",
"n_tot",
")",
"slsp",
".... | restriction on finding the right populations that leave the crystal
field same | [
"restriction",
"on",
"finding",
"the",
"right",
"populations",
"that",
"leave",
"the",
"crystal",
"field",
"same"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/examples/crystal_field.py#L46-L56 |
39,887 | trevisanj/f311 | f311/filetypes/filespectrum.py | FileSpectrum.load | def load(self, filename=None):
"""Method was overriden to set spectrum.filename as well"""
DataFile.load(self, filename)
self.spectrum.filename = filename | python | def load(self, filename=None):
"""Method was overriden to set spectrum.filename as well"""
DataFile.load(self, filename)
self.spectrum.filename = filename | [
"def",
"load",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"DataFile",
".",
"load",
"(",
"self",
",",
"filename",
")",
"self",
".",
"spectrum",
".",
"filename",
"=",
"filename"
] | Method was overriden to set spectrum.filename as well | [
"Method",
"was",
"overriden",
"to",
"set",
"spectrum",
".",
"filename",
"as",
"well"
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/filetypes/filespectrum.py#L25-L28 |
39,888 | trevisanj/f311 | f311/filetypes/filespectrum.py | FileSpectrumFits._do_save_as | def _do_save_as(self, filename):
"""Saves spectrum back to FITS file."""
if len(self.spectrum.x) < 2:
raise RuntimeError("Spectrum must have at least two points")
if os.path.isfile(filename):
os.unlink(filename) # PyFITS does not overwrite file
hdu = self.spect... | python | def _do_save_as(self, filename):
"""Saves spectrum back to FITS file."""
if len(self.spectrum.x) < 2:
raise RuntimeError("Spectrum must have at least two points")
if os.path.isfile(filename):
os.unlink(filename) # PyFITS does not overwrite file
hdu = self.spect... | [
"def",
"_do_save_as",
"(",
"self",
",",
"filename",
")",
":",
"if",
"len",
"(",
"self",
".",
"spectrum",
".",
"x",
")",
"<",
"2",
":",
"raise",
"RuntimeError",
"(",
"\"Spectrum must have at least two points\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
... | Saves spectrum back to FITS file. | [
"Saves",
"spectrum",
"back",
"to",
"FITS",
"file",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/filetypes/filespectrum.py#L74-L83 |
39,889 | hackedd/gw2api | gw2api/wvw.py | matches | def matches():
"""This resource returns a list of the currently running WvW matches, with
the participating worlds included in the result. Further details about a
match can be requested using the ``match_details`` function.
The response is a list of match objects, each of which contains the
followi... | python | def matches():
"""This resource returns a list of the currently running WvW matches, with
the participating worlds included in the result. Further details about a
match can be requested using the ``match_details`` function.
The response is a list of match objects, each of which contains the
followi... | [
"def",
"matches",
"(",
")",
":",
"wvw_matches",
"=",
"get_cached",
"(",
"\"wvw/matches.json\"",
",",
"False",
")",
".",
"get",
"(",
"\"wvw_matches\"",
")",
"for",
"match",
"in",
"wvw_matches",
":",
"match",
"[",
"\"start_time\"",
"]",
"=",
"parse_datetime",
... | This resource returns a list of the currently running WvW matches, with
the participating worlds included in the result. Further details about a
match can be requested using the ``match_details`` function.
The response is a list of match objects, each of which contains the
following properties:
wv... | [
"This",
"resource",
"returns",
"a",
"list",
"of",
"the",
"currently",
"running",
"WvW",
"matches",
"with",
"the",
"participating",
"worlds",
"included",
"in",
"the",
"result",
".",
"Further",
"details",
"about",
"a",
"match",
"can",
"be",
"requested",
"using",... | 5543a78e6e3ed0573b7e84c142c44004b4779eac | https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/wvw.py#L20-L51 |
39,890 | hackedd/gw2api | gw2api/wvw.py | objective_names | def objective_names(lang="en"):
"""This resource returns a list of the localized WvW objective names for
the specified language.
:param lang: The language to query the names for.
:return: A dictionary mapping the objective Ids to the names.
*Note that these are not the names displayed in the game,... | python | def objective_names(lang="en"):
"""This resource returns a list of the localized WvW objective names for
the specified language.
:param lang: The language to query the names for.
:return: A dictionary mapping the objective Ids to the names.
*Note that these are not the names displayed in the game,... | [
"def",
"objective_names",
"(",
"lang",
"=",
"\"en\"",
")",
":",
"params",
"=",
"{",
"\"lang\"",
":",
"lang",
"}",
"cache_name",
"=",
"\"objective_names.%(lang)s.json\"",
"%",
"params",
"data",
"=",
"get_cached",
"(",
"\"wvw/objective_names.json\"",
",",
"cache_nam... | This resource returns a list of the localized WvW objective names for
the specified language.
:param lang: The language to query the names for.
:return: A dictionary mapping the objective Ids to the names.
*Note that these are not the names displayed in the game, but rather the
abstract type.* | [
"This",
"resource",
"returns",
"a",
"list",
"of",
"the",
"localized",
"WvW",
"objective",
"names",
"for",
"the",
"specified",
"language",
"."
] | 5543a78e6e3ed0573b7e84c142c44004b4779eac | https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/wvw.py#L117-L131 |
39,891 | wuher/devil | devil/mappers/xmlmapper.py | XmlMapper._parse_data | def _parse_data(self, data, charset):
""" Parse the xml data into dictionary. """
builder = TreeBuilder(numbermode=self._numbermode)
if isinstance(data,basestring):
xml.sax.parseString(data, builder)
else:
xml.sax.parse(data, builder)
return builder.root[... | python | def _parse_data(self, data, charset):
""" Parse the xml data into dictionary. """
builder = TreeBuilder(numbermode=self._numbermode)
if isinstance(data,basestring):
xml.sax.parseString(data, builder)
else:
xml.sax.parse(data, builder)
return builder.root[... | [
"def",
"_parse_data",
"(",
"self",
",",
"data",
",",
"charset",
")",
":",
"builder",
"=",
"TreeBuilder",
"(",
"numbermode",
"=",
"self",
".",
"_numbermode",
")",
"if",
"isinstance",
"(",
"data",
",",
"basestring",
")",
":",
"xml",
".",
"sax",
".",
"par... | Parse the xml data into dictionary. | [
"Parse",
"the",
"xml",
"data",
"into",
"dictionary",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/mappers/xmlmapper.py#L68-L76 |
39,892 | wuher/devil | devil/mappers/xmlmapper.py | XmlMapper._format_data | def _format_data(self, data, charset):
""" Format data into XML. """
if data is None or data == '':
return u''
stream = StringIO.StringIO()
xml = SimplerXMLGenerator(stream, charset)
xml.startDocument()
xml.startElement(self._root_element_name(), {})
... | python | def _format_data(self, data, charset):
""" Format data into XML. """
if data is None or data == '':
return u''
stream = StringIO.StringIO()
xml = SimplerXMLGenerator(stream, charset)
xml.startDocument()
xml.startElement(self._root_element_name(), {})
... | [
"def",
"_format_data",
"(",
"self",
",",
"data",
",",
"charset",
")",
":",
"if",
"data",
"is",
"None",
"or",
"data",
"==",
"''",
":",
"return",
"u''",
"stream",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"xml",
"=",
"SimplerXMLGenerator",
"(",
"stream... | Format data into XML. | [
"Format",
"data",
"into",
"XML",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/mappers/xmlmapper.py#L78-L91 |
39,893 | wuher/devil | devil/mappers/xmlmapper.py | XmlMapper._to_xml | def _to_xml(self, xml, data, key=None):
""" Recursively convert the data into xml.
This function was originally copied from the
`Piston project <https://bitbucket.org/jespern/django-piston/>`_
It has been modified since.
:param xml: the xml document
:type xml: SimplerXM... | python | def _to_xml(self, xml, data, key=None):
""" Recursively convert the data into xml.
This function was originally copied from the
`Piston project <https://bitbucket.org/jespern/django-piston/>`_
It has been modified since.
:param xml: the xml document
:type xml: SimplerXM... | [
"def",
"_to_xml",
"(",
"self",
",",
"xml",
",",
"data",
",",
"key",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"item",
"in",
"data",
":",
"elemname",
"=",
"self",
".",
"_list_item... | Recursively convert the data into xml.
This function was originally copied from the
`Piston project <https://bitbucket.org/jespern/django-piston/>`_
It has been modified since.
:param xml: the xml document
:type xml: SimplerXMLGenerator
:param data: data to be formatted... | [
"Recursively",
"convert",
"the",
"data",
"into",
"xml",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/mappers/xmlmapper.py#L93-L118 |
39,894 | wuher/devil | devil/mappers/xmlmapper.py | TreeBuilder.startElement | def startElement(self, name, attrs):
""" Initialize new node and store current node into stack. """
self.stack.append((self.current, self.chardata))
self.current = {}
self.chardata = [] | python | def startElement(self, name, attrs):
""" Initialize new node and store current node into stack. """
self.stack.append((self.current, self.chardata))
self.current = {}
self.chardata = [] | [
"def",
"startElement",
"(",
"self",
",",
"name",
",",
"attrs",
")",
":",
"self",
".",
"stack",
".",
"append",
"(",
"(",
"self",
".",
"current",
",",
"self",
".",
"chardata",
")",
")",
"self",
".",
"current",
"=",
"{",
"}",
"self",
".",
"chardata",
... | Initialize new node and store current node into stack. | [
"Initialize",
"new",
"node",
"and",
"store",
"current",
"node",
"into",
"stack",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/mappers/xmlmapper.py#L163-L167 |
39,895 | wuher/devil | devil/mappers/xmlmapper.py | TreeBuilder.endElement | def endElement(self, name):
""" End current xml element, parse and add to to parent node. """
if self.current:
# we have nested elements
obj = self.current
else:
# text only node
text = ''.join(self.chardata).strip()
obj = self._parse_n... | python | def endElement(self, name):
""" End current xml element, parse and add to to parent node. """
if self.current:
# we have nested elements
obj = self.current
else:
# text only node
text = ''.join(self.chardata).strip()
obj = self._parse_n... | [
"def",
"endElement",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"current",
":",
"# we have nested elements",
"obj",
"=",
"self",
".",
"current",
"else",
":",
"# text only node",
"text",
"=",
"''",
".",
"join",
"(",
"self",
".",
"chardata",
")... | End current xml element, parse and add to to parent node. | [
"End",
"current",
"xml",
"element",
"parse",
"and",
"add",
"to",
"to",
"parent",
"node",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/mappers/xmlmapper.py#L169-L179 |
39,896 | wuher/devil | devil/mappers/xmlmapper.py | TreeBuilder._parse_node_data | def _parse_node_data(self, data):
""" Parse the value of a node. Override to provide your own parsing. """
data = data or ''
if self.numbermode == 'basic':
return self._try_parse_basic_number(data)
elif self.numbermode == 'decimal':
return self._try_parse_decimal(... | python | def _parse_node_data(self, data):
""" Parse the value of a node. Override to provide your own parsing. """
data = data or ''
if self.numbermode == 'basic':
return self._try_parse_basic_number(data)
elif self.numbermode == 'decimal':
return self._try_parse_decimal(... | [
"def",
"_parse_node_data",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
"or",
"''",
"if",
"self",
".",
"numbermode",
"==",
"'basic'",
":",
"return",
"self",
".",
"_try_parse_basic_number",
"(",
"data",
")",
"elif",
"self",
".",
"numbermode",
... | Parse the value of a node. Override to provide your own parsing. | [
"Parse",
"the",
"value",
"of",
"a",
"node",
".",
"Override",
"to",
"provide",
"your",
"own",
"parsing",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/mappers/xmlmapper.py#L185-L193 |
39,897 | wuher/devil | devil/mappers/xmlmapper.py | TreeBuilder._try_parse_basic_number | def _try_parse_basic_number(self, data):
""" Try to convert the data into ``int`` or ``float``.
:returns: ``Decimal`` or ``data`` if conversion fails.
"""
# try int first
try:
return int(data)
except ValueError:
pass
# try float next
... | python | def _try_parse_basic_number(self, data):
""" Try to convert the data into ``int`` or ``float``.
:returns: ``Decimal`` or ``data`` if conversion fails.
"""
# try int first
try:
return int(data)
except ValueError:
pass
# try float next
... | [
"def",
"_try_parse_basic_number",
"(",
"self",
",",
"data",
")",
":",
"# try int first",
"try",
":",
"return",
"int",
"(",
"data",
")",
"except",
"ValueError",
":",
"pass",
"# try float next",
"try",
":",
"return",
"float",
"(",
"data",
")",
"except",
"Value... | Try to convert the data into ``int`` or ``float``.
:returns: ``Decimal`` or ``data`` if conversion fails. | [
"Try",
"to",
"convert",
"the",
"data",
"into",
"int",
"or",
"float",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/mappers/xmlmapper.py#L195-L212 |
39,898 | herrersystem/apize | apize/decorators.py | apize_raw | def apize_raw(url, method='GET'):
"""
Convert data and params dict -> json.
"""
def decorator(func):
def wrapper(*args, **kwargs):
elem = func(*args, **kwargs)
if type(elem) is not dict:
raise BadReturnVarType(func.__name__)
response = send_request(url, method,
elem.get('data', {}),
elem.g... | python | def apize_raw(url, method='GET'):
"""
Convert data and params dict -> json.
"""
def decorator(func):
def wrapper(*args, **kwargs):
elem = func(*args, **kwargs)
if type(elem) is not dict:
raise BadReturnVarType(func.__name__)
response = send_request(url, method,
elem.get('data', {}),
elem.g... | [
"def",
"apize_raw",
"(",
"url",
",",
"method",
"=",
"'GET'",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"elem",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwar... | Convert data and params dict -> json. | [
"Convert",
"data",
"and",
"params",
"dict",
"-",
">",
"json",
"."
] | cf491660f0ee1c89a1e87a574eb8cd3c10257597 | https://github.com/herrersystem/apize/blob/cf491660f0ee1c89a1e87a574eb8cd3c10257597/apize/decorators.py#L9-L34 |
39,899 | Bernardo-MG/tox-test-command | setup.py | extract_version | def extract_version(path):
"""
Reads the file at the specified path and returns the version contained in it.
This is meant for reading the __init__.py file inside a package, and so it
expects a version field like:
__version__ = '1.0.0'
:param path: path to the Python file
:return: the ver... | python | def extract_version(path):
"""
Reads the file at the specified path and returns the version contained in it.
This is meant for reading the __init__.py file inside a package, and so it
expects a version field like:
__version__ = '1.0.0'
:param path: path to the Python file
:return: the ver... | [
"def",
"extract_version",
"(",
"path",
")",
":",
"# Regular expression for the version",
"_version_re",
"=",
"re",
".",
"compile",
"(",
"r'__version__\\s+=\\s+(.*)'",
")",
"with",
"open",
"(",
"path",
"+",
"'__init__.py'",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8... | Reads the file at the specified path and returns the version contained in it.
This is meant for reading the __init__.py file inside a package, and so it
expects a version field like:
__version__ = '1.0.0'
:param path: path to the Python file
:return: the version inside the file | [
"Reads",
"the",
"file",
"at",
"the",
"specified",
"path",
"and",
"returns",
"the",
"version",
"contained",
"in",
"it",
"."
] | b8412adae08fa4399fc8b1a33b277aa96dec35c8 | https://github.com/Bernardo-MG/tox-test-command/blob/b8412adae08fa4399fc8b1a33b277aa96dec35c8/setup.py#L35-L65 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.