repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
sprockets/sprockets.http | sprockets/http/app.py | CallbackManager.start | def start(self, io_loop):
"""
Run the ``before_run`` callbacks and queue to ``on_start`` callbacks.
:param tornado.ioloop.IOLoop io_loop: loop to start the app on.
"""
for callback in self.before_run_callbacks:
try:
callback(self.tornado_application,... | python | def start(self, io_loop):
"""
Run the ``before_run`` callbacks and queue to ``on_start`` callbacks.
:param tornado.ioloop.IOLoop io_loop: loop to start the app on.
"""
for callback in self.before_run_callbacks:
try:
callback(self.tornado_application,... | [
"def",
"start",
"(",
"self",
",",
"io_loop",
")",
":",
"for",
"callback",
"in",
"self",
".",
"before_run_callbacks",
":",
"try",
":",
"callback",
"(",
"self",
".",
"tornado_application",
",",
"io_loop",
")",
"except",
"Exception",
":",
"self",
".",
"logger... | Run the ``before_run`` callbacks and queue to ``on_start`` callbacks.
:param tornado.ioloop.IOLoop io_loop: loop to start the app on. | [
"Run",
"the",
"before_run",
"callbacks",
"and",
"queue",
"to",
"on_start",
"callbacks",
"."
] | train | https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/app.py#L87-L104 |
sprockets/sprockets.http | sprockets/http/app.py | CallbackManager.stop | def stop(self, io_loop):
"""
Asynchronously stop the application.
:param tornado.ioloop.IOLoop io_loop: loop to run until all
callbacks, timeouts, and queued calls are complete
Call this method to start the application shutdown process.
The IOLoop will be stopped on... | python | def stop(self, io_loop):
"""
Asynchronously stop the application.
:param tornado.ioloop.IOLoop io_loop: loop to run until all
callbacks, timeouts, and queued calls are complete
Call this method to start the application shutdown process.
The IOLoop will be stopped on... | [
"def",
"stop",
"(",
"self",
",",
"io_loop",
")",
":",
"running_async",
"=",
"False",
"shutdown",
"=",
"_ShutdownHandler",
"(",
"io_loop",
")",
"for",
"callback",
"in",
"self",
".",
"on_shutdown_callbacks",
":",
"try",
":",
"maybe_future",
"=",
"callback",
"(... | Asynchronously stop the application.
:param tornado.ioloop.IOLoop io_loop: loop to run until all
callbacks, timeouts, and queued calls are complete
Call this method to start the application shutdown process.
The IOLoop will be stopped once the application is completely
shut... | [
"Asynchronously",
"stop",
"the",
"application",
"."
] | train | https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/app.py#L106-L136 |
sunlightlabs/django-mediasync | mediasync/__init__.py | combine_files | def combine_files(joinfile, sourcefiles, client):
"""
Given a combo file name (joinfile), combine the sourcefiles into a single
monolithic file.
Returns a string containing the combo file, or None if the specified
file can not be combo'd.
"""
from mediasync.conf import msettings
jo... | python | def combine_files(joinfile, sourcefiles, client):
"""
Given a combo file name (joinfile), combine the sourcefiles into a single
monolithic file.
Returns a string containing the combo file, or None if the specified
file can not be combo'd.
"""
from mediasync.conf import msettings
jo... | [
"def",
"combine_files",
"(",
"joinfile",
",",
"sourcefiles",
",",
"client",
")",
":",
"from",
"mediasync",
".",
"conf",
"import",
"msettings",
"joinfile",
"=",
"joinfile",
".",
"strip",
"(",
"'/'",
")",
"if",
"joinfile",
".",
"endswith",
"(",
"'.css'",
")"... | Given a combo file name (joinfile), combine the sourcefiles into a single
monolithic file.
Returns a string containing the combo file, or None if the specified
file can not be combo'd. | [
"Given",
"a",
"combo",
"file",
"name",
"(",
"joinfile",
")",
"combine",
"the",
"sourcefiles",
"into",
"a",
"single",
"monolithic",
"file",
".",
"Returns",
"a",
"string",
"containing",
"the",
"combo",
"file",
"or",
"None",
"if",
"the",
"specified",
"file",
... | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/__init__.py#L65-L99 |
sunlightlabs/django-mediasync | mediasync/__init__.py | sync | def sync(client=None, force=False, verbose=True):
""" Let's face it... pushing this stuff to S3 is messy.
A lot of different things need to be calculated for each file
and they have to be in a certain order as some variables rely
on others.
"""
from mediasync import backends
from... | python | def sync(client=None, force=False, verbose=True):
""" Let's face it... pushing this stuff to S3 is messy.
A lot of different things need to be calculated for each file
and they have to be in a certain order as some variables rely
on others.
"""
from mediasync import backends
from... | [
"def",
"sync",
"(",
"client",
"=",
"None",
",",
"force",
"=",
"False",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"mediasync",
"import",
"backends",
"from",
"mediasync",
".",
"conf",
"import",
"msettings",
"from",
"mediasync",
".",
"signals",
"import",... | Let's face it... pushing this stuff to S3 is messy.
A lot of different things need to be calculated for each file
and they have to be in a certain order as some variables rely
on others. | [
"Let",
"s",
"face",
"it",
"...",
"pushing",
"this",
"stuff",
"to",
"S3",
"is",
"messy",
".",
"A",
"lot",
"of",
"different",
"things",
"need",
"to",
"be",
"calculated",
"for",
"each",
"file",
"and",
"they",
"have",
"to",
"be",
"in",
"a",
"certain",
"o... | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/__init__.py#L101-L173 |
VitorRamos/cpufreq | cpufreq/cpufreq.py | cpuFreq.enable_all_cpu | def enable_all_cpu(self):
'''
Enable all offline cpus
'''
for cpu in self.__get_ranges("offline"):
fpath = path.join("cpu%i"%cpu,"online")
self.__write_cpu_file(fpath, b"1") | python | def enable_all_cpu(self):
'''
Enable all offline cpus
'''
for cpu in self.__get_ranges("offline"):
fpath = path.join("cpu%i"%cpu,"online")
self.__write_cpu_file(fpath, b"1") | [
"def",
"enable_all_cpu",
"(",
"self",
")",
":",
"for",
"cpu",
"in",
"self",
".",
"__get_ranges",
"(",
"\"offline\"",
")",
":",
"fpath",
"=",
"path",
".",
"join",
"(",
"\"cpu%i\"",
"%",
"cpu",
",",
"\"online\"",
")",
"self",
".",
"__write_cpu_file",
"(",
... | Enable all offline cpus | [
"Enable",
"all",
"offline",
"cpus"
] | train | https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L93-L99 |
VitorRamos/cpufreq | cpufreq/cpufreq.py | cpuFreq.reset | def reset(self, rg=None):
'''
Enable all offline cpus, and reset max and min frequencies files
rg: range or list of threads to reset
'''
if type(rg) == int:
rg= [rg]
to_reset= rg if rg else self.__get_ranges("present")
self.enable_cpu(to_reset)
... | python | def reset(self, rg=None):
'''
Enable all offline cpus, and reset max and min frequencies files
rg: range or list of threads to reset
'''
if type(rg) == int:
rg= [rg]
to_reset= rg if rg else self.__get_ranges("present")
self.enable_cpu(to_reset)
... | [
"def",
"reset",
"(",
"self",
",",
"rg",
"=",
"None",
")",
":",
"if",
"type",
"(",
"rg",
")",
"==",
"int",
":",
"rg",
"=",
"[",
"rg",
"]",
"to_reset",
"=",
"rg",
"if",
"rg",
"else",
"self",
".",
"__get_ranges",
"(",
"\"present\"",
")",
"self",
"... | Enable all offline cpus, and reset max and min frequencies files
rg: range or list of threads to reset | [
"Enable",
"all",
"offline",
"cpus",
"and",
"reset",
"max",
"and",
"min",
"frequencies",
"files"
] | train | https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L101-L120 |
VitorRamos/cpufreq | cpufreq/cpufreq.py | cpuFreq.disable_hyperthread | def disable_hyperthread(self):
'''
Disable all threads attached to the same core
'''
to_disable = []
online_cpus = self.__get_ranges("online")
for cpu in online_cpus:
fpath = path.join("cpu%i"%cpu,"topology","thread_siblings_list")
to_disable += se... | python | def disable_hyperthread(self):
'''
Disable all threads attached to the same core
'''
to_disable = []
online_cpus = self.__get_ranges("online")
for cpu in online_cpus:
fpath = path.join("cpu%i"%cpu,"topology","thread_siblings_list")
to_disable += se... | [
"def",
"disable_hyperthread",
"(",
"self",
")",
":",
"to_disable",
"=",
"[",
"]",
"online_cpus",
"=",
"self",
".",
"__get_ranges",
"(",
"\"online\"",
")",
"for",
"cpu",
"in",
"online_cpus",
":",
"fpath",
"=",
"path",
".",
"join",
"(",
"\"cpu%i\"",
"%",
"... | Disable all threads attached to the same core | [
"Disable",
"all",
"threads",
"attached",
"to",
"the",
"same",
"core"
] | train | https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L122-L135 |
VitorRamos/cpufreq | cpufreq/cpufreq.py | cpuFreq.disable_cpu | def disable_cpu(self, rg):
'''
Disable cpus
rg: range or list of threads to disable
'''
if type(rg) == int:
rg= [rg]
to_disable= set(rg) & set(self.__get_ranges("online"))
for cpu in to_disable:
fpath = path.join("cpu%i"%cpu,"online")
... | python | def disable_cpu(self, rg):
'''
Disable cpus
rg: range or list of threads to disable
'''
if type(rg) == int:
rg= [rg]
to_disable= set(rg) & set(self.__get_ranges("online"))
for cpu in to_disable:
fpath = path.join("cpu%i"%cpu,"online")
... | [
"def",
"disable_cpu",
"(",
"self",
",",
"rg",
")",
":",
"if",
"type",
"(",
"rg",
")",
"==",
"int",
":",
"rg",
"=",
"[",
"rg",
"]",
"to_disable",
"=",
"set",
"(",
"rg",
")",
"&",
"set",
"(",
"self",
".",
"__get_ranges",
"(",
"\"online\"",
")",
"... | Disable cpus
rg: range or list of threads to disable | [
"Disable",
"cpus"
] | train | https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L137-L148 |
VitorRamos/cpufreq | cpufreq/cpufreq.py | cpuFreq.enable_cpu | def enable_cpu(self, rg):
'''
Enable cpus
rg: range or list of threads to enable
'''
if type(rg) == int:
rg= [rg]
to_disable= set(rg) & set(self.__get_ranges("offline"))
for cpu in to_disable:
fpath = path.join("cpu%i"%cpu,"online")
... | python | def enable_cpu(self, rg):
'''
Enable cpus
rg: range or list of threads to enable
'''
if type(rg) == int:
rg= [rg]
to_disable= set(rg) & set(self.__get_ranges("offline"))
for cpu in to_disable:
fpath = path.join("cpu%i"%cpu,"online")
... | [
"def",
"enable_cpu",
"(",
"self",
",",
"rg",
")",
":",
"if",
"type",
"(",
"rg",
")",
"==",
"int",
":",
"rg",
"=",
"[",
"rg",
"]",
"to_disable",
"=",
"set",
"(",
"rg",
")",
"&",
"set",
"(",
"self",
".",
"__get_ranges",
"(",
"\"offline\"",
")",
"... | Enable cpus
rg: range or list of threads to enable | [
"Enable",
"cpus"
] | train | https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L150-L161 |
VitorRamos/cpufreq | cpufreq/cpufreq.py | cpuFreq.set_frequencies | def set_frequencies(self, freq, rg=None, setMaxfeq=True, setMinfreq=True, setSpeed=True):
'''
Set cores frequencies
freq: int frequency in KHz
rg: list of range of cores
setMaxfeq: set the maximum frequency, default to true
setMinfreq: set the minimum frequency, default ... | python | def set_frequencies(self, freq, rg=None, setMaxfeq=True, setMinfreq=True, setSpeed=True):
'''
Set cores frequencies
freq: int frequency in KHz
rg: list of range of cores
setMaxfeq: set the maximum frequency, default to true
setMinfreq: set the minimum frequency, default ... | [
"def",
"set_frequencies",
"(",
"self",
",",
"freq",
",",
"rg",
"=",
"None",
",",
"setMaxfeq",
"=",
"True",
",",
"setMinfreq",
"=",
"True",
",",
"setSpeed",
"=",
"True",
")",
":",
"to_change",
"=",
"self",
".",
"__get_ranges",
"(",
"\"online\"",
")",
"i... | Set cores frequencies
freq: int frequency in KHz
rg: list of range of cores
setMaxfeq: set the maximum frequency, default to true
setMinfreq: set the minimum frequency, default to true
setSpeed: only set the frequency, default to true | [
"Set",
"cores",
"frequencies"
] | train | https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L163-L186 |
VitorRamos/cpufreq | cpufreq/cpufreq.py | cpuFreq.set_governors | def set_governors(self, gov, rg=None):
'''
Set governors
gov: str name of the governor
rg: list of range of cores
'''
to_change = self.__get_ranges("online")
if type(rg) == int:
rg= [rg]
if rg: to_change= set(rg) & set(self.__get_ranges("onlin... | python | def set_governors(self, gov, rg=None):
'''
Set governors
gov: str name of the governor
rg: list of range of cores
'''
to_change = self.__get_ranges("online")
if type(rg) == int:
rg= [rg]
if rg: to_change= set(rg) & set(self.__get_ranges("onlin... | [
"def",
"set_governors",
"(",
"self",
",",
"gov",
",",
"rg",
"=",
"None",
")",
":",
"to_change",
"=",
"self",
".",
"__get_ranges",
"(",
"\"online\"",
")",
"if",
"type",
"(",
"rg",
")",
"==",
"int",
":",
"rg",
"=",
"[",
"rg",
"]",
"if",
"rg",
":",
... | Set governors
gov: str name of the governor
rg: list of range of cores | [
"Set",
"governors"
] | train | https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L188-L201 |
VitorRamos/cpufreq | cpufreq/cpufreq.py | cpuFreq.get_available_frequencies | def get_available_frequencies(self):
'''
Get all possible frequencies
'''
fpath = path.join("cpu0","cpufreq","scaling_available_frequencies")
data = self.__read_cpu_file(fpath).rstrip("\n").split()
return data | python | def get_available_frequencies(self):
'''
Get all possible frequencies
'''
fpath = path.join("cpu0","cpufreq","scaling_available_frequencies")
data = self.__read_cpu_file(fpath).rstrip("\n").split()
return data | [
"def",
"get_available_frequencies",
"(",
"self",
")",
":",
"fpath",
"=",
"path",
".",
"join",
"(",
"\"cpu0\"",
",",
"\"cpufreq\"",
",",
"\"scaling_available_frequencies\"",
")",
"data",
"=",
"self",
".",
"__read_cpu_file",
"(",
"fpath",
")",
".",
"rstrip",
"("... | Get all possible frequencies | [
"Get",
"all",
"possible",
"frequencies"
] | train | https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L203-L209 |
codeforamerica/three | three/core.py | Three.configure | def configure(self, endpoint=None, **kwargs):
"""Configure a previously initialized instance of the class."""
if endpoint:
kwargs['endpoint'] = endpoint
keywords = self._keywords.copy()
keywords.update(kwargs)
if 'endpoint' in kwargs:
# Then we need to cor... | python | def configure(self, endpoint=None, **kwargs):
"""Configure a previously initialized instance of the class."""
if endpoint:
kwargs['endpoint'] = endpoint
keywords = self._keywords.copy()
keywords.update(kwargs)
if 'endpoint' in kwargs:
# Then we need to cor... | [
"def",
"configure",
"(",
"self",
",",
"endpoint",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"endpoint",
":",
"kwargs",
"[",
"'endpoint'",
"]",
"=",
"endpoint",
"keywords",
"=",
"self",
".",
"_keywords",
".",
"copy",
"(",
")",
"keywords",
... | Configure a previously initialized instance of the class. | [
"Configure",
"a",
"previously",
"initialized",
"instance",
"of",
"the",
"class",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L66-L87 |
codeforamerica/three | three/core.py | Three._configure_endpoint | def _configure_endpoint(self, endpoint):
"""Configure the endpoint with a schema and end slash."""
if not endpoint.startswith('http'):
endpoint = 'https://' + endpoint
if not endpoint.endswith('/'):
endpoint += '/'
return endpoint | python | def _configure_endpoint(self, endpoint):
"""Configure the endpoint with a schema and end slash."""
if not endpoint.startswith('http'):
endpoint = 'https://' + endpoint
if not endpoint.endswith('/'):
endpoint += '/'
return endpoint | [
"def",
"_configure_endpoint",
"(",
"self",
",",
"endpoint",
")",
":",
"if",
"not",
"endpoint",
".",
"startswith",
"(",
"'http'",
")",
":",
"endpoint",
"=",
"'https://'",
"+",
"endpoint",
"if",
"not",
"endpoint",
".",
"endswith",
"(",
"'/'",
")",
":",
"en... | Configure the endpoint with a schema and end slash. | [
"Configure",
"the",
"endpoint",
"with",
"a",
"schema",
"and",
"end",
"slash",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L89-L95 |
codeforamerica/three | three/core.py | Three.get | def get(self, *args, **kwargs):
"""Perform a get request."""
if 'convert' in kwargs:
conversion = kwargs.pop('convert')
else:
conversion = True
kwargs = self._get_keywords(**kwargs)
url = self._create_path(*args)
request = self.session.get(url, par... | python | def get(self, *args, **kwargs):
"""Perform a get request."""
if 'convert' in kwargs:
conversion = kwargs.pop('convert')
else:
conversion = True
kwargs = self._get_keywords(**kwargs)
url = self._create_path(*args)
request = self.session.get(url, par... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'convert'",
"in",
"kwargs",
":",
"conversion",
"=",
"kwargs",
".",
"pop",
"(",
"'convert'",
")",
"else",
":",
"conversion",
"=",
"True",
"kwargs",
"=",
"self",
"... | Perform a get request. | [
"Perform",
"a",
"get",
"request",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L107-L118 |
codeforamerica/three | three/core.py | Three._get_keywords | def _get_keywords(self, **kwargs):
"""Format GET request parameters and keywords."""
if self.jurisdiction and 'jurisdiction_id' not in kwargs:
kwargs['jurisdiction_id'] = self.jurisdiction
if 'count' in kwargs:
kwargs['page_size'] = kwargs.pop('count')
if 'start' ... | python | def _get_keywords(self, **kwargs):
"""Format GET request parameters and keywords."""
if self.jurisdiction and 'jurisdiction_id' not in kwargs:
kwargs['jurisdiction_id'] = self.jurisdiction
if 'count' in kwargs:
kwargs['page_size'] = kwargs.pop('count')
if 'start' ... | [
"def",
"_get_keywords",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"jurisdiction",
"and",
"'jurisdiction_id'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'jurisdiction_id'",
"]",
"=",
"self",
".",
"jurisdiction",
"if",
"'count'",
"... | Format GET request parameters and keywords. | [
"Format",
"GET",
"request",
"parameters",
"and",
"keywords",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L120-L140 |
codeforamerica/three | three/core.py | Three._format_dates | def _format_dates(self, start, end):
"""Format start and end dates."""
start = self._split_date(start)
end = self._split_date(end)
return start, end | python | def _format_dates(self, start, end):
"""Format start and end dates."""
start = self._split_date(start)
end = self._split_date(end)
return start, end | [
"def",
"_format_dates",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"start",
"=",
"self",
".",
"_split_date",
"(",
"start",
")",
"end",
"=",
"self",
".",
"_split_date",
"(",
"end",
")",
"return",
"start",
",",
"end"
] | Format start and end dates. | [
"Format",
"start",
"and",
"end",
"dates",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L142-L146 |
codeforamerica/three | three/core.py | Three._split_date | def _split_date(self, time):
"""Split apart a date string."""
if isinstance(time, str):
month, day, year = [int(t) for t in re.split(r'-|/', time)]
if year < 100:
# Quick hack for dates < 2000.
year += 2000
time = date(year, month, day)... | python | def _split_date(self, time):
"""Split apart a date string."""
if isinstance(time, str):
month, day, year = [int(t) for t in re.split(r'-|/', time)]
if year < 100:
# Quick hack for dates < 2000.
year += 2000
time = date(year, month, day)... | [
"def",
"_split_date",
"(",
"self",
",",
"time",
")",
":",
"if",
"isinstance",
"(",
"time",
",",
"str",
")",
":",
"month",
",",
"day",
",",
"year",
"=",
"[",
"int",
"(",
"t",
")",
"for",
"t",
"in",
"re",
".",
"split",
"(",
"r'-|/'",
",",
"time",... | Split apart a date string. | [
"Split",
"apart",
"a",
"date",
"string",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L148-L156 |
codeforamerica/three | three/core.py | Three.convert | def convert(self, content, conversion):
"""Convert content to Python data structures."""
if not conversion:
data = content
elif self.format == 'json':
data = json.loads(content)
elif self.format == 'xml':
content = xml(content)
first = list... | python | def convert(self, content, conversion):
"""Convert content to Python data structures."""
if not conversion:
data = content
elif self.format == 'json':
data = json.loads(content)
elif self.format == 'xml':
content = xml(content)
first = list... | [
"def",
"convert",
"(",
"self",
",",
"content",
",",
"conversion",
")",
":",
"if",
"not",
"conversion",
":",
"data",
"=",
"content",
"elif",
"self",
".",
"format",
"==",
"'json'",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"content",
")",
"elif",
"s... | Convert content to Python data structures. | [
"Convert",
"content",
"to",
"Python",
"data",
"structures",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L158-L170 |
codeforamerica/three | three/core.py | Three.discovery | def discovery(self, url=None):
"""
Retrieve the standard discovery file that provides routing
information.
>>> Three().discovery()
{'discovery': 'data'}
"""
if url:
data = self.session.get(url).content
elif self.discovery_url:
resp... | python | def discovery(self, url=None):
"""
Retrieve the standard discovery file that provides routing
information.
>>> Three().discovery()
{'discovery': 'data'}
"""
if url:
data = self.session.get(url).content
elif self.discovery_url:
resp... | [
"def",
"discovery",
"(",
"self",
",",
"url",
"=",
"None",
")",
":",
"if",
"url",
":",
"data",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
")",
".",
"content",
"elif",
"self",
".",
"discovery_url",
":",
"response",
"=",
"self",
".",
"sessio... | Retrieve the standard discovery file that provides routing
information.
>>> Three().discovery()
{'discovery': 'data'} | [
"Retrieve",
"the",
"standard",
"discovery",
"file",
"that",
"provides",
"routing",
"information",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L172-L192 |
codeforamerica/three | three/core.py | Three.services | def services(self, code=None, **kwargs):
"""
Retrieve information about available services. You can also enter a
specific service code argument.
>>> Three().services()
{'all': {'service_code': 'data'}}
>>> Three().services('033')
{'033': {'service_code': 'data'}}... | python | def services(self, code=None, **kwargs):
"""
Retrieve information about available services. You can also enter a
specific service code argument.
>>> Three().services()
{'all': {'service_code': 'data'}}
>>> Three().services('033')
{'033': {'service_code': 'data'}}... | [
"def",
"services",
"(",
"self",
",",
"code",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"get",
"(",
"'services'",
",",
"code",
",",
"*",
"*",
"kwargs",
")",
"return",
"data"
] | Retrieve information about available services. You can also enter a
specific service code argument.
>>> Three().services()
{'all': {'service_code': 'data'}}
>>> Three().services('033')
{'033': {'service_code': 'data'}} | [
"Retrieve",
"information",
"about",
"available",
"services",
".",
"You",
"can",
"also",
"enter",
"a",
"specific",
"service",
"code",
"argument",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L194-L205 |
codeforamerica/three | three/core.py | Three.requests | def requests(self, code=None, **kwargs):
"""
Retrieve open requests. You can also enter a specific service code
argument.
>>> Three('api.city.gov').requests()
{'all': {'requests': 'data'}}
>>> Three('api.city.gov').requests('123')
{'123': {'requests': 'data'}}
... | python | def requests(self, code=None, **kwargs):
"""
Retrieve open requests. You can also enter a specific service code
argument.
>>> Three('api.city.gov').requests()
{'all': {'requests': 'data'}}
>>> Three('api.city.gov').requests('123')
{'123': {'requests': 'data'}}
... | [
"def",
"requests",
"(",
"self",
",",
"code",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"code",
":",
"kwargs",
"[",
"'service_code'",
"]",
"=",
"code",
"data",
"=",
"self",
".",
"get",
"(",
"'requests'",
",",
"*",
"*",
"kwargs",
")",
"... | Retrieve open requests. You can also enter a specific service code
argument.
>>> Three('api.city.gov').requests()
{'all': {'requests': 'data'}}
>>> Three('api.city.gov').requests('123')
{'123': {'requests': 'data'}} | [
"Retrieve",
"open",
"requests",
".",
"You",
"can",
"also",
"enter",
"a",
"specific",
"service",
"code",
"argument",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L207-L220 |
codeforamerica/three | three/core.py | Three.request | def request(self, id, **kwargs):
"""
Retrieve a specific request using its service code ID.
>>> Three('api.city.gov').request('12345')
{'request': {'service_code': {'12345': 'data'}}}
"""
data = self.get('requests', id, **kwargs)
return data | python | def request(self, id, **kwargs):
"""
Retrieve a specific request using its service code ID.
>>> Three('api.city.gov').request('12345')
{'request': {'service_code': {'12345': 'data'}}}
"""
data = self.get('requests', id, **kwargs)
return data | [
"def",
"request",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"get",
"(",
"'requests'",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
"return",
"data"
] | Retrieve a specific request using its service code ID.
>>> Three('api.city.gov').request('12345')
{'request': {'service_code': {'12345': 'data'}}} | [
"Retrieve",
"a",
"specific",
"request",
"using",
"its",
"service",
"code",
"ID",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L222-L230 |
codeforamerica/three | three/core.py | Three.post | def post(self, service_code='0', **kwargs):
"""
Post a new Open311 request.
>>> t = Three('api.city.gov')
>>> t.post('123', address='123 Any St', name='Zach Williams',
... phone='555-5555', description='My issue description.',
... media=open('photo.png', 'r... | python | def post(self, service_code='0', **kwargs):
"""
Post a new Open311 request.
>>> t = Three('api.city.gov')
>>> t.post('123', address='123 Any St', name='Zach Williams',
... phone='555-5555', description='My issue description.',
... media=open('photo.png', 'r... | [
"def",
"post",
"(",
"self",
",",
"service_code",
"=",
"'0'",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'service_code'",
"]",
"=",
"service_code",
"kwargs",
"=",
"self",
".",
"_post_keywords",
"(",
"*",
"*",
"kwargs",
")",
"media",
"=",
"kwargs... | Post a new Open311 request.
>>> t = Three('api.city.gov')
>>> t.post('123', address='123 Any St', name='Zach Williams',
... phone='555-5555', description='My issue description.',
... media=open('photo.png', 'rb'))
{'successful': {'request': 'post'}} | [
"Post",
"a",
"new",
"Open311",
"request",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L232-L257 |
codeforamerica/three | three/core.py | Three._post_keywords | def _post_keywords(self, **kwargs):
"""Configure keyword arguments for Open311 POST requests."""
if self.jurisdiction and 'jurisdiction_id' not in kwargs:
kwargs['jurisdiction_id'] = self.jurisdiction
if 'address' in kwargs:
address = kwargs.pop('address')
kwa... | python | def _post_keywords(self, **kwargs):
"""Configure keyword arguments for Open311 POST requests."""
if self.jurisdiction and 'jurisdiction_id' not in kwargs:
kwargs['jurisdiction_id'] = self.jurisdiction
if 'address' in kwargs:
address = kwargs.pop('address')
kwa... | [
"def",
"_post_keywords",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"jurisdiction",
"and",
"'jurisdiction_id'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'jurisdiction_id'",
"]",
"=",
"self",
".",
"jurisdiction",
"if",
"'address'",
... | Configure keyword arguments for Open311 POST requests. | [
"Configure",
"keyword",
"arguments",
"for",
"Open311",
"POST",
"requests",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L259-L272 |
codeforamerica/three | three/core.py | Three.token | def token(self, id, **kwargs):
"""
Retrieve a service request ID from a token.
>>> Three('api.city.gov').token('12345')
{'service_request_id': {'for': {'token': '12345'}}}
"""
data = self.get('tokens', id, **kwargs)
return data | python | def token(self, id, **kwargs):
"""
Retrieve a service request ID from a token.
>>> Three('api.city.gov').token('12345')
{'service_request_id': {'for': {'token': '12345'}}}
"""
data = self.get('tokens', id, **kwargs)
return data | [
"def",
"token",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"get",
"(",
"'tokens'",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
"return",
"data"
] | Retrieve a service request ID from a token.
>>> Three('api.city.gov').token('12345')
{'service_request_id': {'for': {'token': '12345'}}} | [
"Retrieve",
"a",
"service",
"request",
"ID",
"from",
"a",
"token",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L274-L282 |
matllubos/django-is-core | is_core/utils/compatibility.py | CompatibilityWidgetMixin.build_attrs | def build_attrs(self, base_attrs, extra_attrs=None, **kwargs):
"""
Helper function for building an attribute dictionary.
This is combination of the same method from Django<=1.10 and Django1.11+
"""
attrs = dict(base_attrs, **kwargs)
if extra_attrs:
attrs.upda... | python | def build_attrs(self, base_attrs, extra_attrs=None, **kwargs):
"""
Helper function for building an attribute dictionary.
This is combination of the same method from Django<=1.10 and Django1.11+
"""
attrs = dict(base_attrs, **kwargs)
if extra_attrs:
attrs.upda... | [
"def",
"build_attrs",
"(",
"self",
",",
"base_attrs",
",",
"extra_attrs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"dict",
"(",
"base_attrs",
",",
"*",
"*",
"kwargs",
")",
"if",
"extra_attrs",
":",
"attrs",
".",
"update",
"(",
"e... | Helper function for building an attribute dictionary.
This is combination of the same method from Django<=1.10 and Django1.11+ | [
"Helper",
"function",
"for",
"building",
"an",
"attribute",
"dictionary",
".",
"This",
"is",
"combination",
"of",
"the",
"same",
"method",
"from",
"Django<",
"=",
"1",
".",
"10",
"and",
"Django1",
".",
"11",
"+"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/compatibility.py#L74-L83 |
xapple/plumbing | plumbing/csv_tables.py | CSVTable.to_dataframe | def to_dataframe(self, **kwargs):
"""Load up the CSV file as a pandas dataframe"""
return pandas.io.parsers.read_csv(self.path, sep=self.d, **kwargs) | python | def to_dataframe(self, **kwargs):
"""Load up the CSV file as a pandas dataframe"""
return pandas.io.parsers.read_csv(self.path, sep=self.d, **kwargs) | [
"def",
"to_dataframe",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"pandas",
".",
"io",
".",
"parsers",
".",
"read_csv",
"(",
"self",
".",
"path",
",",
"sep",
"=",
"self",
".",
"d",
",",
"*",
"*",
"kwargs",
")"
] | Load up the CSV file as a pandas dataframe | [
"Load",
"up",
"the",
"CSV",
"file",
"as",
"a",
"pandas",
"dataframe"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/csv_tables.py#L61-L63 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.get_elementary_intervals | def get_elementary_intervals(self, features):
"""Generates a sorted list of elementary intervals"""
coords = []
try:
for interval in features:
if len(interval) != 3:
raise SyntaxError('Interval malformed %s. Allways specify start and end position f... | python | def get_elementary_intervals(self, features):
"""Generates a sorted list of elementary intervals"""
coords = []
try:
for interval in features:
if len(interval) != 3:
raise SyntaxError('Interval malformed %s. Allways specify start and end position f... | [
"def",
"get_elementary_intervals",
"(",
"self",
",",
"features",
")",
":",
"coords",
"=",
"[",
"]",
"try",
":",
"for",
"interval",
"in",
"features",
":",
"if",
"len",
"(",
"interval",
")",
"!=",
"3",
":",
"raise",
"SyntaxError",
"(",
"'Interval malformed %... | Generates a sorted list of elementary intervals | [
"Generates",
"a",
"sorted",
"list",
"of",
"elementary",
"intervals"
] | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L50-L62 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.recursive_build_tree | def recursive_build_tree(self, intervals):
"""
recursively builds a BST based on the elementary intervals.
each node is an array: [interval value, left descendent nodes, right descendent nodes, [ids]].
nodes with no descendents have a -1 value in left/right descendent positions.
... | python | def recursive_build_tree(self, intervals):
"""
recursively builds a BST based on the elementary intervals.
each node is an array: [interval value, left descendent nodes, right descendent nodes, [ids]].
nodes with no descendents have a -1 value in left/right descendent positions.
... | [
"def",
"recursive_build_tree",
"(",
"self",
",",
"intervals",
")",
":",
"center",
"=",
"int",
"(",
"round",
"(",
"len",
"(",
"intervals",
")",
"/",
"2",
")",
")",
"left",
"=",
"intervals",
"[",
":",
"center",
"]",
"right",
"=",
"intervals",
"[",
"cen... | recursively builds a BST based on the elementary intervals.
each node is an array: [interval value, left descendent nodes, right descendent nodes, [ids]].
nodes with no descendents have a -1 value in left/right descendent positions.
for example, a node with two empty descendents:
[5... | [
"recursively",
"builds",
"a",
"BST",
"based",
"on",
"the",
"elementary",
"intervals",
".",
"each",
"node",
"is",
"an",
"array",
":",
"[",
"interval",
"value",
"left",
"descendent",
"nodes",
"right",
"descendent",
"nodes",
"[",
"ids",
"]]",
".",
"nodes",
"w... | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L64-L97 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.pt_within | def pt_within(self, pt, subject):
"""Accessory function to check if a point is within a range"""
try:
if pt >= int(subject[0]) and pt <= int(subject[1]):
return True
except ValueError:
raise ValueError('Interval start and stop has to be integers. %s' % str... | python | def pt_within(self, pt, subject):
"""Accessory function to check if a point is within a range"""
try:
if pt >= int(subject[0]) and pt <= int(subject[1]):
return True
except ValueError:
raise ValueError('Interval start and stop has to be integers. %s' % str... | [
"def",
"pt_within",
"(",
"self",
",",
"pt",
",",
"subject",
")",
":",
"try",
":",
"if",
"pt",
">=",
"int",
"(",
"subject",
"[",
"0",
"]",
")",
"and",
"pt",
"<=",
"int",
"(",
"subject",
"[",
"1",
"]",
")",
":",
"return",
"True",
"except",
"Value... | Accessory function to check if a point is within a range | [
"Accessory",
"function",
"to",
"check",
"if",
"a",
"point",
"is",
"within",
"a",
"range"
] | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L99-L107 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.is_within | def is_within(self, query, subject):
"""Accessory function to check if a range is fully within another range"""
if self.pt_within(query[0], subject) and self.pt_within(query[1], subject):
return True
return False | python | def is_within(self, query, subject):
"""Accessory function to check if a range is fully within another range"""
if self.pt_within(query[0], subject) and self.pt_within(query[1], subject):
return True
return False | [
"def",
"is_within",
"(",
"self",
",",
"query",
",",
"subject",
")",
":",
"if",
"self",
".",
"pt_within",
"(",
"query",
"[",
"0",
"]",
",",
"subject",
")",
"and",
"self",
".",
"pt_within",
"(",
"query",
"[",
"1",
"]",
",",
"subject",
")",
":",
"re... | Accessory function to check if a range is fully within another range | [
"Accessory",
"function",
"to",
"check",
"if",
"a",
"range",
"is",
"fully",
"within",
"another",
"range"
] | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L109-L114 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.overlap | def overlap(self, query, subject):
"""Accessory function to check if two ranges overlap"""
if (self.pt_within(query[0], subject) or self.pt_within(query[1], subject) or
self.pt_within(subject[0], query) or self.pt_within(subject[1], query)):
return True
return False | python | def overlap(self, query, subject):
"""Accessory function to check if two ranges overlap"""
if (self.pt_within(query[0], subject) or self.pt_within(query[1], subject) or
self.pt_within(subject[0], query) or self.pt_within(subject[1], query)):
return True
return False | [
"def",
"overlap",
"(",
"self",
",",
"query",
",",
"subject",
")",
":",
"if",
"(",
"self",
".",
"pt_within",
"(",
"query",
"[",
"0",
"]",
",",
"subject",
")",
"or",
"self",
".",
"pt_within",
"(",
"query",
"[",
"1",
"]",
",",
"subject",
")",
"or",
... | Accessory function to check if two ranges overlap | [
"Accessory",
"function",
"to",
"check",
"if",
"two",
"ranges",
"overlap"
] | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L116-L122 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.recursive_insert | def recursive_insert(self, node, coord, data, start, end):
"""Recursively inserts id data into nodes"""
if node[0] != -1:
left = (start, node[0])
right = (node[0], end)
#if left is totally within coord
if self.is_within(left, coord):
node[... | python | def recursive_insert(self, node, coord, data, start, end):
"""Recursively inserts id data into nodes"""
if node[0] != -1:
left = (start, node[0])
right = (node[0], end)
#if left is totally within coord
if self.is_within(left, coord):
node[... | [
"def",
"recursive_insert",
"(",
"self",
",",
"node",
",",
"coord",
",",
"data",
",",
"start",
",",
"end",
")",
":",
"if",
"node",
"[",
"0",
"]",
"!=",
"-",
"1",
":",
"left",
"=",
"(",
"start",
",",
"node",
"[",
"0",
"]",
")",
"right",
"=",
"(... | Recursively inserts id data into nodes | [
"Recursively",
"inserts",
"id",
"data",
"into",
"nodes"
] | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L124-L139 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.insert_data | def insert_data(self, node, data, start, end):
"""loops through all the data and inserts them into the empty tree"""
for item in data:
self.recursive_insert(node, [item[0], item[1]], item[-1], start, end) | python | def insert_data(self, node, data, start, end):
"""loops through all the data and inserts them into the empty tree"""
for item in data:
self.recursive_insert(node, [item[0], item[1]], item[-1], start, end) | [
"def",
"insert_data",
"(",
"self",
",",
"node",
",",
"data",
",",
"start",
",",
"end",
")",
":",
"for",
"item",
"in",
"data",
":",
"self",
".",
"recursive_insert",
"(",
"node",
",",
"[",
"item",
"[",
"0",
"]",
",",
"item",
"[",
"1",
"]",
"]",
"... | loops through all the data and inserts them into the empty tree | [
"loops",
"through",
"all",
"the",
"data",
"and",
"inserts",
"them",
"into",
"the",
"empty",
"tree"
] | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L141-L144 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.trim_tree | def trim_tree(self, node):
"""trims the tree for any empty data nodes"""
data_len = len(node[-1])
if node[1] == -1 and node[2] == -1:
if data_len == 0:
return 1
else:
return 0
else:
if self.trim_tree(node[1]) == 1:
... | python | def trim_tree(self, node):
"""trims the tree for any empty data nodes"""
data_len = len(node[-1])
if node[1] == -1 and node[2] == -1:
if data_len == 0:
return 1
else:
return 0
else:
if self.trim_tree(node[1]) == 1:
... | [
"def",
"trim_tree",
"(",
"self",
",",
"node",
")",
":",
"data_len",
"=",
"len",
"(",
"node",
"[",
"-",
"1",
"]",
")",
"if",
"node",
"[",
"1",
"]",
"==",
"-",
"1",
"and",
"node",
"[",
"2",
"]",
"==",
"-",
"1",
":",
"if",
"data_len",
"==",
"0... | trims the tree for any empty data nodes | [
"trims",
"the",
"tree",
"for",
"any",
"empty",
"data",
"nodes"
] | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L146-L166 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.find | def find(self, node, interval, start, end):
"""recursively finds ids within a range"""
data = []
if len(interval) != 2:
raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval))
left = (start, node[0])
... | python | def find(self, node, interval, start, end):
"""recursively finds ids within a range"""
data = []
if len(interval) != 2:
raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval))
left = (start, node[0])
... | [
"def",
"find",
"(",
"self",
",",
"node",
",",
"interval",
",",
"start",
",",
"end",
")",
":",
"data",
"=",
"[",
"]",
"if",
"len",
"(",
"interval",
")",
"!=",
"2",
":",
"raise",
"SyntaxError",
"(",
"'Interval malformed %s. Allways specify start and end positi... | recursively finds ids within a range | [
"recursively",
"finds",
"ids",
"within",
"a",
"range"
] | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L168-L188 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.find_range | def find_range(self, interval):
"""wrapper for find"""
return self.find(self.tree, interval, self.start, self.end) | python | def find_range(self, interval):
"""wrapper for find"""
return self.find(self.tree, interval, self.start, self.end) | [
"def",
"find_range",
"(",
"self",
",",
"interval",
")",
":",
"return",
"self",
".",
"find",
"(",
"self",
".",
"tree",
",",
"interval",
",",
"self",
".",
"start",
",",
"self",
".",
"end",
")"
] | wrapper for find | [
"wrapper",
"for",
"find"
] | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L190-L192 |
moonso/interval_tree | interval_tree/interval_tree.py | IntervalTree.pprint | def pprint(self, ind):
"""pretty prints the tree with indentation"""
pp = pprint.PrettyPrinter(indent=ind)
pp.pprint(self.tree) | python | def pprint(self, ind):
"""pretty prints the tree with indentation"""
pp = pprint.PrettyPrinter(indent=ind)
pp.pprint(self.tree) | [
"def",
"pprint",
"(",
"self",
",",
"ind",
")",
":",
"pp",
"=",
"pprint",
".",
"PrettyPrinter",
"(",
"indent",
"=",
"ind",
")",
"pp",
".",
"pprint",
"(",
"self",
".",
"tree",
")"
] | pretty prints the tree with indentation | [
"pretty",
"prints",
"the",
"tree",
"with",
"indentation"
] | train | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L194-L197 |
matllubos/django-is-core | is_core/site.py | get_model_core | def get_model_core(model):
"""
Return core view of given model or None
"""
model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name))
return registered_model_cores.get(model_label) | python | def get_model_core(model):
"""
Return core view of given model or None
"""
model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name))
return registered_model_cores.get(model_label) | [
"def",
"get_model_core",
"(",
"model",
")",
":",
"model_label",
"=",
"lower",
"(",
"'%s.%s'",
"%",
"(",
"model",
".",
"_meta",
".",
"app_label",
",",
"model",
".",
"_meta",
".",
"object_name",
")",
")",
"return",
"registered_model_cores",
".",
"get",
"(",
... | Return core view of given model or None | [
"Return",
"core",
"view",
"of",
"given",
"model",
"or",
"None"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/site.py#L28-L33 |
vcs-python/libvcs | libvcs/shortcuts.py | create_repo | def create_repo(url, vcs, **kwargs):
r"""Return a object representation of a VCS repository.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
>>> from libvcs.shortcuts... | python | def create_repo(url, vcs, **kwargs):
r"""Return a object representation of a VCS repository.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
>>> from libvcs.shortcuts... | [
"def",
"create_repo",
"(",
"url",
",",
"vcs",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"vcs",
"==",
"'git'",
":",
"return",
"GitRepo",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"elif",
"vcs",
"==",
"'hg'",
":",
"return",
"MercurialRepo",
"(",
"url"... | r"""Return a object representation of a VCS repository.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
>>> from libvcs.shortcuts import create_repo
>>> r = crea... | [
"r",
"Return",
"a",
"object",
"representation",
"of",
"a",
"VCS",
"repository",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/shortcuts.py#L8-L43 |
vcs-python/libvcs | libvcs/shortcuts.py | create_repo_from_pip_url | def create_repo_from_pip_url(pip_url, **kwargs):
r"""Return a object representation of a VCS repository via pip-style url.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
... | python | def create_repo_from_pip_url(pip_url, **kwargs):
r"""Return a object representation of a VCS repository via pip-style url.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
... | [
"def",
"create_repo_from_pip_url",
"(",
"pip_url",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"pip_url",
".",
"startswith",
"(",
"'git+'",
")",
":",
"return",
"GitRepo",
".",
"from_pip_url",
"(",
"pip_url",
",",
"*",
"*",
"kwargs",
")",
"elif",
"pip_url",
... | r"""Return a object representation of a VCS repository via pip-style url.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
>>> from libvcs.shortcuts import create_repo_fro... | [
"r",
"Return",
"a",
"object",
"representation",
"of",
"a",
"VCS",
"repository",
"via",
"pip",
"-",
"style",
"url",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/shortcuts.py#L46-L80 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.set_paths | def set_paths(self, base_dir, script_path):
"""Set the directory, the script path and the outfile path"""
# Make absolute paths #
if 'change_dir' in self.kwargs:
self.kwargs['change_dir'] = DirectoryPath(os.path.abspath(self.kwargs['change_dir']))
if 'out_file' in self.kwargs... | python | def set_paths(self, base_dir, script_path):
"""Set the directory, the script path and the outfile path"""
# Make absolute paths #
if 'change_dir' in self.kwargs:
self.kwargs['change_dir'] = DirectoryPath(os.path.abspath(self.kwargs['change_dir']))
if 'out_file' in self.kwargs... | [
"def",
"set_paths",
"(",
"self",
",",
"base_dir",
",",
"script_path",
")",
":",
"# Make absolute paths #",
"if",
"'change_dir'",
"in",
"self",
".",
"kwargs",
":",
"self",
".",
"kwargs",
"[",
"'change_dir'",
"]",
"=",
"DirectoryPath",
"(",
"os",
".",
"path",
... | Set the directory, the script path and the outfile path | [
"Set",
"the",
"directory",
"the",
"script",
"path",
"and",
"the",
"outfile",
"path"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L121-L136 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.slurm_params | def slurm_params(self):
"""The list of parameters to give to the `sbatch` command."""
# Main loop #
result = OrderedDict()
for param, info in self.slurm_headers.items():
if not info['needed'] and not param in self.kwargs: continue
if param in self.kwargs: result[p... | python | def slurm_params(self):
"""The list of parameters to give to the `sbatch` command."""
# Main loop #
result = OrderedDict()
for param, info in self.slurm_headers.items():
if not info['needed'] and not param in self.kwargs: continue
if param in self.kwargs: result[p... | [
"def",
"slurm_params",
"(",
"self",
")",
":",
"# Main loop #",
"result",
"=",
"OrderedDict",
"(",
")",
"for",
"param",
",",
"info",
"in",
"self",
".",
"slurm_headers",
".",
"items",
"(",
")",
":",
"if",
"not",
"info",
"[",
"'needed'",
"]",
"and",
"not"... | The list of parameters to give to the `sbatch` command. | [
"The",
"list",
"of",
"parameters",
"to",
"give",
"to",
"the",
"sbatch",
"command",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L139-L150 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.script | def script(self):
"""The script to be submitted to the SLURM queue."""
self.shebang_header = self.shebang_headers[self.language]
self.slurm_header = [self.slurm_headers[k]['tag'] % v for k,v in self.slurm_params.items()]
self.script_header = self.script_headers[self.language]
... | python | def script(self):
"""The script to be submitted to the SLURM queue."""
self.shebang_header = self.shebang_headers[self.language]
self.slurm_header = [self.slurm_headers[k]['tag'] % v for k,v in self.slurm_params.items()]
self.script_header = self.script_headers[self.language]
... | [
"def",
"script",
"(",
"self",
")",
":",
"self",
".",
"shebang_header",
"=",
"self",
".",
"shebang_headers",
"[",
"self",
".",
"language",
"]",
"self",
".",
"slurm_header",
"=",
"[",
"self",
".",
"slurm_headers",
"[",
"k",
"]",
"[",
"'tag'",
"]",
"%",
... | The script to be submitted to the SLURM queue. | [
"The",
"script",
"to",
"be",
"submitted",
"to",
"the",
"SLURM",
"queue",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L153-L163 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.make_script | def make_script(self):
"""Make the script and return a FilePath object pointing to the script above."""
self.script_path.write(self.script)
self.script_path.permissions.make_executable()
return self.script_path | python | def make_script(self):
"""Make the script and return a FilePath object pointing to the script above."""
self.script_path.write(self.script)
self.script_path.permissions.make_executable()
return self.script_path | [
"def",
"make_script",
"(",
"self",
")",
":",
"self",
".",
"script_path",
".",
"write",
"(",
"self",
".",
"script",
")",
"self",
".",
"script_path",
".",
"permissions",
".",
"make_executable",
"(",
")",
"return",
"self",
".",
"script_path"
] | Make the script and return a FilePath object pointing to the script above. | [
"Make",
"the",
"script",
"and",
"return",
"a",
"FilePath",
"object",
"pointing",
"to",
"the",
"script",
"above",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L165-L169 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.status | def status(self):
"""What is the status of the job ?"""
# If there is no script it is either ready or a lost duplicate #
if not self.script_path.exists:
if self.name in jobs.names: return "DUPLICATE"
if self.name not in jobs.names: return "READY"
# It is submi... | python | def status(self):
"""What is the status of the job ?"""
# If there is no script it is either ready or a lost duplicate #
if not self.script_path.exists:
if self.name in jobs.names: return "DUPLICATE"
if self.name not in jobs.names: return "READY"
# It is submi... | [
"def",
"status",
"(",
"self",
")",
":",
"# If there is no script it is either ready or a lost duplicate #",
"if",
"not",
"self",
".",
"script_path",
".",
"exists",
":",
"if",
"self",
".",
"name",
"in",
"jobs",
".",
"names",
":",
"return",
"\"DUPLICATE\"",
"if",
... | What is the status of the job ? | [
"What",
"is",
"the",
"status",
"of",
"the",
"job",
"?"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L183-L201 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.info | def info(self):
"""Get the existing job information dictionary"""
if self.name not in jobs: return {'status': self.status}
else: return jobs[self.name] | python | def info(self):
"""Get the existing job information dictionary"""
if self.name not in jobs: return {'status': self.status}
else: return jobs[self.name] | [
"def",
"info",
"(",
"self",
")",
":",
"if",
"self",
".",
"name",
"not",
"in",
"jobs",
":",
"return",
"{",
"'status'",
":",
"self",
".",
"status",
"}",
"else",
":",
"return",
"jobs",
"[",
"self",
".",
"name",
"]"
] | Get the existing job information dictionary | [
"Get",
"the",
"existing",
"job",
"information",
"dictionary"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L204-L207 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.run | def run(self):
"""Will call self.launch() after performing some checks"""
# Check already exists #
if self.status == "READY": return self.launch()
# Check name conflict #
if self.status == "DUPLICATE": message = "Job with same name '%s' already in queue, but we lost the script."... | python | def run(self):
"""Will call self.launch() after performing some checks"""
# Check already exists #
if self.status == "READY": return self.launch()
# Check name conflict #
if self.status == "DUPLICATE": message = "Job with same name '%s' already in queue, but we lost the script."... | [
"def",
"run",
"(",
"self",
")",
":",
"# Check already exists #",
"if",
"self",
".",
"status",
"==",
"\"READY\"",
":",
"return",
"self",
".",
"launch",
"(",
")",
"# Check name conflict #",
"if",
"self",
".",
"status",
"==",
"\"DUPLICATE\"",
":",
"message",
"=... | Will call self.launch() after performing some checks | [
"Will",
"call",
"self",
".",
"launch",
"()",
"after",
"performing",
"some",
"checks"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L210-L223 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.launch | def launch(self):
"""Make the script file and return the newly created job id"""
# Make script file #
self.make_script()
# Do it #
sbatch_out = sh.sbatch(self.script_path)
jobs.expire()
# Message #
print Color.i_blu + "SLURM:" + Color.end + " " + str(sbatc... | python | def launch(self):
"""Make the script file and return the newly created job id"""
# Make script file #
self.make_script()
# Do it #
sbatch_out = sh.sbatch(self.script_path)
jobs.expire()
# Message #
print Color.i_blu + "SLURM:" + Color.end + " " + str(sbatc... | [
"def",
"launch",
"(",
"self",
")",
":",
"# Make script file #",
"self",
".",
"make_script",
"(",
")",
"# Do it #",
"sbatch_out",
"=",
"sh",
".",
"sbatch",
"(",
"self",
".",
"script_path",
")",
"jobs",
".",
"expire",
"(",
")",
"# Message #",
"print",
"Color... | Make the script file and return the newly created job id | [
"Make",
"the",
"script",
"file",
"and",
"return",
"the",
"newly",
"created",
"job",
"id"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L225-L236 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.run_locally | def run_locally(self):
"""A convenience method to run the same result as a SLURM job
but locally in a non-blocking way. Useful for testing."""
self.thread = threading.Thread(target=self.execute_locally)
self.thread.daemon = True # So that they die when we die
self.thread.start() | python | def run_locally(self):
"""A convenience method to run the same result as a SLURM job
but locally in a non-blocking way. Useful for testing."""
self.thread = threading.Thread(target=self.execute_locally)
self.thread.daemon = True # So that they die when we die
self.thread.start() | [
"def",
"run_locally",
"(",
"self",
")",
":",
"self",
".",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"execute_locally",
")",
"self",
".",
"thread",
".",
"daemon",
"=",
"True",
"# So that they die when we die",
"self",
".",
... | A convenience method to run the same result as a SLURM job
but locally in a non-blocking way. Useful for testing. | [
"A",
"convenience",
"method",
"to",
"run",
"the",
"same",
"result",
"as",
"a",
"SLURM",
"job",
"but",
"locally",
"in",
"a",
"non",
"-",
"blocking",
"way",
".",
"Useful",
"for",
"testing",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L248-L253 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.execute_locally | def execute_locally(self):
"""Runs the equivalent command locally in a blocking way."""
# Make script file #
self.make_script()
# Do it #
with open(self.kwargs['out_file'], 'w') as handle:
sh.python(self.script_path, _out=handle, _err=handle) | python | def execute_locally(self):
"""Runs the equivalent command locally in a blocking way."""
# Make script file #
self.make_script()
# Do it #
with open(self.kwargs['out_file'], 'w') as handle:
sh.python(self.script_path, _out=handle, _err=handle) | [
"def",
"execute_locally",
"(",
"self",
")",
":",
"# Make script file #",
"self",
".",
"make_script",
"(",
")",
"# Do it #",
"with",
"open",
"(",
"self",
".",
"kwargs",
"[",
"'out_file'",
"]",
",",
"'w'",
")",
"as",
"handle",
":",
"sh",
".",
"python",
"("... | Runs the equivalent command locally in a blocking way. | [
"Runs",
"the",
"equivalent",
"command",
"locally",
"in",
"a",
"blocking",
"way",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L255-L261 |
xapple/plumbing | plumbing/slurm/job.py | JobSLURM.wait_locally | def wait_locally(self):
"""If you have run the query in a non-blocking way, call this method to pause
until the query is finished."""
try: self.thread.join(sys.maxint) # maxint timeout so that we can Ctrl-C them
except KeyboardInterrupt: print "Stopped waiting on job '%s'" % self.kwargs[... | python | def wait_locally(self):
"""If you have run the query in a non-blocking way, call this method to pause
until the query is finished."""
try: self.thread.join(sys.maxint) # maxint timeout so that we can Ctrl-C them
except KeyboardInterrupt: print "Stopped waiting on job '%s'" % self.kwargs[... | [
"def",
"wait_locally",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"thread",
".",
"join",
"(",
"sys",
".",
"maxint",
")",
"# maxint timeout so that we can Ctrl-C them",
"except",
"KeyboardInterrupt",
":",
"print",
"\"Stopped waiting on job '%s'\"",
"%",
"self",
... | If you have run the query in a non-blocking way, call this method to pause
until the query is finished. | [
"If",
"you",
"have",
"run",
"the",
"query",
"in",
"a",
"non",
"-",
"blocking",
"way",
"call",
"this",
"method",
"to",
"pause",
"until",
"the",
"query",
"is",
"finished",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L263-L267 |
Infinidat/infi.projector | src/infi/projector/plugins/builtins/version/__init__.py | VersionPlugin.replace_version_tag | def replace_version_tag(self):
"""find the next major/minor/trivial version number if applicable"""
version_tag = self.arguments.get('<version>')
special_keywords = ['current', 'latest']
if version_tag in special_keywords:
logger.error("releasing version '{}' is disallowed. D... | python | def replace_version_tag(self):
"""find the next major/minor/trivial version number if applicable"""
version_tag = self.arguments.get('<version>')
special_keywords = ['current', 'latest']
if version_tag in special_keywords:
logger.error("releasing version '{}' is disallowed. D... | [
"def",
"replace_version_tag",
"(",
"self",
")",
":",
"version_tag",
"=",
"self",
".",
"arguments",
".",
"get",
"(",
"'<version>'",
")",
"special_keywords",
"=",
"[",
"'current'",
",",
"'latest'",
"]",
"if",
"version_tag",
"in",
"special_keywords",
":",
"logger... | find the next major/minor/trivial version number if applicable | [
"find",
"the",
"next",
"major",
"/",
"minor",
"/",
"trivial",
"version",
"number",
"if",
"applicable"
] | train | https://github.com/Infinidat/infi.projector/blob/4a0d098f4f8f14ffb3e7536c7515fa79a21c1134/src/infi/projector/plugins/builtins/version/__init__.py#L40-L58 |
Infinidat/infi.projector | src/infi/projector/commandline_parser/__init__.py | parse_docopt_string | def parse_docopt_string(docopt_string):
"""returns a 2-tuple (usage, options)"""
from re import match, DOTALL
only_usage_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+"""
usage_and_options_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+Options:\s+(?P<options>.*)\s+"""
usage, options = '', ''
if match(usa... | python | def parse_docopt_string(docopt_string):
"""returns a 2-tuple (usage, options)"""
from re import match, DOTALL
only_usage_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+"""
usage_and_options_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+Options:\s+(?P<options>.*)\s+"""
usage, options = '', ''
if match(usa... | [
"def",
"parse_docopt_string",
"(",
"docopt_string",
")",
":",
"from",
"re",
"import",
"match",
",",
"DOTALL",
"only_usage_pattern",
"=",
"r\"\"\"\\s+Usage:\\s+(?P<usage>.*)\\s+\"\"\"",
"usage_and_options_pattern",
"=",
"r\"\"\"\\s+Usage:\\s+(?P<usage>.*)\\s+Options:\\s+(?P<options>... | returns a 2-tuple (usage, options) | [
"returns",
"a",
"2",
"-",
"tuple",
"(",
"usage",
"options",
")"
] | train | https://github.com/Infinidat/infi.projector/blob/4a0d098f4f8f14ffb3e7536c7515fa79a21c1134/src/infi/projector/commandline_parser/__init__.py#L8-L19 |
matllubos/django-is-core | is_core/filters/__init__.py | UIFilterMixin.get_widget | def get_widget(self, request):
"""
Returns concrete widget that will be used for rendering table filter.
"""
widget = self.widget
if isinstance(widget, type):
widget = widget()
return widget | python | def get_widget(self, request):
"""
Returns concrete widget that will be used for rendering table filter.
"""
widget = self.widget
if isinstance(widget, type):
widget = widget()
return widget | [
"def",
"get_widget",
"(",
"self",
",",
"request",
")",
":",
"widget",
"=",
"self",
".",
"widget",
"if",
"isinstance",
"(",
"widget",
",",
"type",
")",
":",
"widget",
"=",
"widget",
"(",
")",
"return",
"widget"
] | Returns concrete widget that will be used for rendering table filter. | [
"Returns",
"concrete",
"widget",
"that",
"will",
"be",
"used",
"for",
"rendering",
"table",
"filter",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/filters/__init__.py#L38-L45 |
sunlightlabs/django-mediasync | mediasync/backends/s3.py | Client.remote_media_url | def remote_media_url(self, with_ssl=False):
"""
Returns the base remote media URL. In this case, we can safely make
some assumptions on the URL string based on bucket names, and having
public ACL on.
args:
with_ssl: (bool) If True, return an HTTPS url.
... | python | def remote_media_url(self, with_ssl=False):
"""
Returns the base remote media URL. In this case, we can safely make
some assumptions on the URL string based on bucket names, and having
public ACL on.
args:
with_ssl: (bool) If True, return an HTTPS url.
... | [
"def",
"remote_media_url",
"(",
"self",
",",
"with_ssl",
"=",
"False",
")",
":",
"protocol",
"=",
"'http'",
"if",
"with_ssl",
"is",
"False",
"else",
"'https'",
"url",
"=",
"(",
"self",
".",
"aws_bucket_cname",
"and",
"\"%s://%s\"",
"or",
"\"%s://s3.amazonaws.c... | Returns the base remote media URL. In this case, we can safely make
some assumptions on the URL string based on bucket names, and having
public ACL on.
args:
with_ssl: (bool) If True, return an HTTPS url. | [
"Returns",
"the",
"base",
"remote",
"media",
"URL",
".",
"In",
"this",
"case",
"we",
"can",
"safely",
"make",
"some",
"assumptions",
"on",
"the",
"URL",
"string",
"based",
"on",
"bucket",
"names",
"and",
"having",
"public",
"ACL",
"on",
".",
"args",
":",... | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/backends/s3.py#L43-L56 |
softwarefactory-project/distroinfo | scripts/di.py | distroinfo | def distroinfo(cargs, version=__version__):
"""
distroinfo Command-Line Interface
"""
code = 1
args = docopt(__doc__, argv=cargs)
try:
if args['--version']:
if not version:
version = 'N/A'
print(version)
code = 0
elif args['fet... | python | def distroinfo(cargs, version=__version__):
"""
distroinfo Command-Line Interface
"""
code = 1
args = docopt(__doc__, argv=cargs)
try:
if args['--version']:
if not version:
version = 'N/A'
print(version)
code = 0
elif args['fet... | [
"def",
"distroinfo",
"(",
"cargs",
",",
"version",
"=",
"__version__",
")",
":",
"code",
"=",
"1",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"argv",
"=",
"cargs",
")",
"try",
":",
"if",
"args",
"[",
"'--version'",
"]",
":",
"if",
"not",
"version",
... | distroinfo Command-Line Interface | [
"distroinfo",
"Command",
"-",
"Line",
"Interface"
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/scripts/di.py#L95-L132 |
matllubos/django-is-core | is_core/rest/resource.py | RESTResourceMixin._get_error_response | def _get_error_response(self, exception):
"""
Trasform pyston exceptions to Is-core exceptions and raise it
"""
response_exceptions = {
MimerDataException: HTTPBadRequestResponseException,
NotAllowedException: HTTPForbiddenResponseException,
Unsupporte... | python | def _get_error_response(self, exception):
"""
Trasform pyston exceptions to Is-core exceptions and raise it
"""
response_exceptions = {
MimerDataException: HTTPBadRequestResponseException,
NotAllowedException: HTTPForbiddenResponseException,
Unsupporte... | [
"def",
"_get_error_response",
"(",
"self",
",",
"exception",
")",
":",
"response_exceptions",
"=",
"{",
"MimerDataException",
":",
"HTTPBadRequestResponseException",
",",
"NotAllowedException",
":",
"HTTPForbiddenResponseException",
",",
"UnsupportedMediaTypeException",
":",
... | Trasform pyston exceptions to Is-core exceptions and raise it | [
"Trasform",
"pyston",
"exceptions",
"to",
"Is",
"-",
"core",
"exceptions",
"and",
"raise",
"it"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/rest/resource.py#L138-L155 |
dgtony/afg | afg/scenarios.py | Supervisor.reprompt_error | def reprompt_error(self, message=None):
"""
Intended to be used in case of erroneous input data
"""
try:
session_id = session.sessionId
self.session_machines.rollback_fsm(session_id)
current_state = self.session_machines.current_state(session_id)
... | python | def reprompt_error(self, message=None):
"""
Intended to be used in case of erroneous input data
"""
try:
session_id = session.sessionId
self.session_machines.rollback_fsm(session_id)
current_state = self.session_machines.current_state(session_id)
... | [
"def",
"reprompt_error",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"try",
":",
"session_id",
"=",
"session",
".",
"sessionId",
"self",
".",
"session_machines",
".",
"rollback_fsm",
"(",
"session_id",
")",
"current_state",
"=",
"self",
".",
"session... | Intended to be used in case of erroneous input data | [
"Intended",
"to",
"be",
"used",
"in",
"case",
"of",
"erroneous",
"input",
"data"
] | train | https://github.com/dgtony/afg/blob/831ad4c6d158610393dc21e74277d4ed6a004afd/afg/scenarios.py#L116-L131 |
dgtony/afg | afg/scenarios.py | Supervisor.move_to_step | def move_to_step(self, step):
"""
Use in cases when you need to move in given step depending on input
"""
if step not in self._scenario_steps.keys():
raise UndefinedState("step {} not defined in scenario".format(step))
try:
session_id = session.sessionId
... | python | def move_to_step(self, step):
"""
Use in cases when you need to move in given step depending on input
"""
if step not in self._scenario_steps.keys():
raise UndefinedState("step {} not defined in scenario".format(step))
try:
session_id = session.sessionId
... | [
"def",
"move_to_step",
"(",
"self",
",",
"step",
")",
":",
"if",
"step",
"not",
"in",
"self",
".",
"_scenario_steps",
".",
"keys",
"(",
")",
":",
"raise",
"UndefinedState",
"(",
"\"step {} not defined in scenario\"",
".",
"format",
"(",
"step",
")",
")",
"... | Use in cases when you need to move in given step depending on input | [
"Use",
"in",
"cases",
"when",
"you",
"need",
"to",
"move",
"in",
"given",
"step",
"depending",
"on",
"input"
] | train | https://github.com/dgtony/afg/blob/831ad4c6d158610393dc21e74277d4ed6a004afd/afg/scenarios.py#L133-L144 |
dgtony/afg | afg/scenarios.py | Supervisor.get_current_state | def get_current_state(self):
"""
Get current state for user session or None if session doesn't exist
"""
try:
session_id = session.sessionId
return self.session_machines.current_state(session_id)
except UninitializedStateMachine as e:
logger.er... | python | def get_current_state(self):
"""
Get current state for user session or None if session doesn't exist
"""
try:
session_id = session.sessionId
return self.session_machines.current_state(session_id)
except UninitializedStateMachine as e:
logger.er... | [
"def",
"get_current_state",
"(",
"self",
")",
":",
"try",
":",
"session_id",
"=",
"session",
".",
"sessionId",
"return",
"self",
".",
"session_machines",
".",
"current_state",
"(",
"session_id",
")",
"except",
"UninitializedStateMachine",
"as",
"e",
":",
"logger... | Get current state for user session or None if session doesn't exist | [
"Get",
"current",
"state",
"for",
"user",
"session",
"or",
"None",
"if",
"session",
"doesn",
"t",
"exist"
] | train | https://github.com/dgtony/afg/blob/831ad4c6d158610393dc21e74277d4ed6a004afd/afg/scenarios.py#L146-L154 |
dgtony/afg | afg/scenarios.py | Supervisor.get_help | def get_help(self):
"""
Get context help, depending on the current step. If no help for current step
was specified in scenario description file, default one will be returned.
"""
current_state = self.get_current_state()
if current_state is None:
return stateme... | python | def get_help(self):
"""
Get context help, depending on the current step. If no help for current step
was specified in scenario description file, default one will be returned.
"""
current_state = self.get_current_state()
if current_state is None:
return stateme... | [
"def",
"get_help",
"(",
"self",
")",
":",
"current_state",
"=",
"self",
".",
"get_current_state",
"(",
")",
"if",
"current_state",
"is",
"None",
":",
"return",
"statement",
"(",
"INTERNAL_ERROR_MSG",
")",
"else",
":",
"try",
":",
"return",
"choice",
"(",
"... | Get context help, depending on the current step. If no help for current step
was specified in scenario description file, default one will be returned. | [
"Get",
"context",
"help",
"depending",
"on",
"the",
"current",
"step",
".",
"If",
"no",
"help",
"for",
"current",
"step",
"was",
"specified",
"in",
"scenario",
"description",
"file",
"default",
"one",
"will",
"be",
"returned",
"."
] | train | https://github.com/dgtony/afg/blob/831ad4c6d158610393dc21e74277d4ed6a004afd/afg/scenarios.py#L156-L168 |
confirm/ansibleci | ansibleci/runner.py | Runner.run | def run(self):
'''
Runs all enabled tests.
'''
# Run all tests.
for cls in self.get_test_classes():
# Print informational message.
self.logger.info('Running {cls.__name__} test...'.format(cls=cls))
# Create new test instance.
test... | python | def run(self):
'''
Runs all enabled tests.
'''
# Run all tests.
for cls in self.get_test_classes():
# Print informational message.
self.logger.info('Running {cls.__name__} test...'.format(cls=cls))
# Create new test instance.
test... | [
"def",
"run",
"(",
"self",
")",
":",
"# Run all tests.",
"for",
"cls",
"in",
"self",
".",
"get_test_classes",
"(",
")",
":",
"# Print informational message.",
"self",
".",
"logger",
".",
"info",
"(",
"'Running {cls.__name__} test...'",
".",
"format",
"(",
"cls",... | Runs all enabled tests. | [
"Runs",
"all",
"enabled",
"tests",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/runner.py#L71-L97 |
xapple/plumbing | plumbing/dependencies.py | check_executable | def check_executable(tool_name):
"""Raises an warning if the executable *tool_name* is not found."""
result = subprocess.call(['which', tool_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result != 0:
message = "The executable '%s' cannot be found in your $PATH" % tool_name
raise ... | python | def check_executable(tool_name):
"""Raises an warning if the executable *tool_name* is not found."""
result = subprocess.call(['which', tool_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result != 0:
message = "The executable '%s' cannot be found in your $PATH" % tool_name
raise ... | [
"def",
"check_executable",
"(",
"tool_name",
")",
":",
"result",
"=",
"subprocess",
".",
"call",
"(",
"[",
"'which'",
",",
"tool_name",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"if",
"result"... | Raises an warning if the executable *tool_name* is not found. | [
"Raises",
"an",
"warning",
"if",
"the",
"executable",
"*",
"tool_name",
"*",
"is",
"not",
"found",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/dependencies.py#L20-L25 |
xapple/plumbing | plumbing/dependencies.py | check_module | def check_module(mod_name):
"""Calls sys.exit() if the module *mod_name* is not found."""
# Special cases #
if mod_name in module_name: mod_name = module_name[mod_name]
# Use a try except block #
try:
__import__(mod_name)
except ImportError as e:
if str(e) != 'No module named %s'... | python | def check_module(mod_name):
"""Calls sys.exit() if the module *mod_name* is not found."""
# Special cases #
if mod_name in module_name: mod_name = module_name[mod_name]
# Use a try except block #
try:
__import__(mod_name)
except ImportError as e:
if str(e) != 'No module named %s'... | [
"def",
"check_module",
"(",
"mod_name",
")",
":",
"# Special cases #",
"if",
"mod_name",
"in",
"module_name",
":",
"mod_name",
"=",
"module_name",
"[",
"mod_name",
"]",
"# Use a try except block #",
"try",
":",
"__import__",
"(",
"mod_name",
")",
"except",
"Import... | Calls sys.exit() if the module *mod_name* is not found. | [
"Calls",
"sys",
".",
"exit",
"()",
"if",
"the",
"module",
"*",
"mod_name",
"*",
"is",
"not",
"found",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/dependencies.py#L28-L40 |
inveniosoftware/invenio-iiif | invenio_iiif/utils.py | iiif_image_key | def iiif_image_key(obj):
"""Generate the IIIF image key."""
if isinstance(obj, ObjectVersion):
bucket_id = obj.bucket_id
version_id = obj.version_id
key = obj.key
else:
bucket_id = obj.get('bucket')
version_id = obj.get('version_id')
key = obj.get('key')
r... | python | def iiif_image_key(obj):
"""Generate the IIIF image key."""
if isinstance(obj, ObjectVersion):
bucket_id = obj.bucket_id
version_id = obj.version_id
key = obj.key
else:
bucket_id = obj.get('bucket')
version_id = obj.get('version_id')
key = obj.get('key')
r... | [
"def",
"iiif_image_key",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ObjectVersion",
")",
":",
"bucket_id",
"=",
"obj",
".",
"bucket_id",
"version_id",
"=",
"obj",
".",
"version_id",
"key",
"=",
"obj",
".",
"key",
"else",
":",
"bucket_id"... | Generate the IIIF image key. | [
"Generate",
"the",
"IIIF",
"image",
"key",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/utils.py#L18-L32 |
inveniosoftware/invenio-iiif | invenio_iiif/utils.py | ui_iiif_image_url | def ui_iiif_image_url(obj, version='v2', region='full', size='full',
rotation=0, quality='default', image_format='png'):
"""Generate IIIF image URL from the UI application."""
return u'{prefix}{version}/{identifier}/{region}/{size}/{rotation}/' \
u'{quality}.{image_format}'.format(... | python | def ui_iiif_image_url(obj, version='v2', region='full', size='full',
rotation=0, quality='default', image_format='png'):
"""Generate IIIF image URL from the UI application."""
return u'{prefix}{version}/{identifier}/{region}/{size}/{rotation}/' \
u'{quality}.{image_format}'.format(... | [
"def",
"ui_iiif_image_url",
"(",
"obj",
",",
"version",
"=",
"'v2'",
",",
"region",
"=",
"'full'",
",",
"size",
"=",
"'full'",
",",
"rotation",
"=",
"0",
",",
"quality",
"=",
"'default'",
",",
"image_format",
"=",
"'png'",
")",
":",
"return",
"u'{prefix}... | Generate IIIF image URL from the UI application. | [
"Generate",
"IIIF",
"image",
"URL",
"from",
"the",
"UI",
"application",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/utils.py#L35-L49 |
IwoHerka/sexpr | sexpr/types/non_terminal.py | NonTerminal.matches | def matches(self, sexp):
'''
Body of a non-terminal is always a :class:`Sequence`. For an s-expr
to match, it must be of the form::
['name'] + [sexpr-0, ..., sexpr-n]
where the first list contains a name of the non-terminal,
and the second one matches its body seque... | python | def matches(self, sexp):
'''
Body of a non-terminal is always a :class:`Sequence`. For an s-expr
to match, it must be of the form::
['name'] + [sexpr-0, ..., sexpr-n]
where the first list contains a name of the non-terminal,
and the second one matches its body seque... | [
"def",
"matches",
"(",
"self",
",",
"sexp",
")",
":",
"if",
"sexp",
"and",
"isinstance",
"(",
"sexp",
",",
"list",
")",
"and",
"self",
".",
"name",
"==",
"sexp",
"[",
"0",
"]",
":",
"return",
"self",
".",
"body",
".",
"matches",
"(",
"sexp",
"[",... | Body of a non-terminal is always a :class:`Sequence`. For an s-expr
to match, it must be of the form::
['name'] + [sexpr-0, ..., sexpr-n]
where the first list contains a name of the non-terminal,
and the second one matches its body sequence. | [
"Body",
"of",
"a",
"non",
"-",
"terminal",
"is",
"always",
"a",
":",
"class",
":",
"Sequence",
".",
"For",
"an",
"s",
"-",
"expr",
"to",
"match",
"it",
"must",
"be",
"of",
"the",
"form",
"::"
] | train | https://github.com/IwoHerka/sexpr/blob/28e32f543a127bbbf832b2dba7cb93f9e57db3b6/sexpr/types/non_terminal.py#L9-L21 |
inveniosoftware/invenio-iiif | invenio_iiif/previewer.py | preview | def preview(file):
"""Render appropriate template with embed flag."""
params = deepcopy(current_app.config['IIIF_PREVIEWER_PARAMS'])
if 'image_format' not in params:
params['image_format'] = \
'png' if file.has_extensions('.png') else 'jpg'
return render_template(
current_app... | python | def preview(file):
"""Render appropriate template with embed flag."""
params = deepcopy(current_app.config['IIIF_PREVIEWER_PARAMS'])
if 'image_format' not in params:
params['image_format'] = \
'png' if file.has_extensions('.png') else 'jpg'
return render_template(
current_app... | [
"def",
"preview",
"(",
"file",
")",
":",
"params",
"=",
"deepcopy",
"(",
"current_app",
".",
"config",
"[",
"'IIIF_PREVIEWER_PARAMS'",
"]",
")",
"if",
"'image_format'",
"not",
"in",
"params",
":",
"params",
"[",
"'image_format'",
"]",
"=",
"'png'",
"if",
"... | Render appropriate template with embed flag. | [
"Render",
"appropriate",
"template",
"with",
"embed",
"flag",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/previewer.py#L35-L48 |
intelligenia/modeltranslation | modeltranslation/templatetags/modeltranslation_tags.py | get_translated_attribute | def get_translated_attribute(instance, attr):
"""
Wraps Django Model __getattribute__ method making translation in templates less painful
"""
# If its class has no translatable fields, returns attribute
try:
if not hasattr(instance._meta, "translatable_fields") or len(getattr(instance._meta,"translatable_field... | python | def get_translated_attribute(instance, attr):
"""
Wraps Django Model __getattribute__ method making translation in templates less painful
"""
# If its class has no translatable fields, returns attribute
try:
if not hasattr(instance._meta, "translatable_fields") or len(getattr(instance._meta,"translatable_field... | [
"def",
"get_translated_attribute",
"(",
"instance",
",",
"attr",
")",
":",
"# If its class has no translatable fields, returns attribute",
"try",
":",
"if",
"not",
"hasattr",
"(",
"instance",
".",
"_meta",
",",
"\"translatable_fields\"",
")",
"or",
"len",
"(",
"getatt... | Wraps Django Model __getattribute__ method making translation in templates less painful | [
"Wraps",
"Django",
"Model",
"__getattribute__",
"method",
"making",
"translation",
"in",
"templates",
"less",
"painful"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/templatetags/modeltranslation_tags.py#L15-L47 |
The-Politico/django-slackchat-serializer | slackchat/authentication.py | secure | def secure(view):
"""Set an auth decorator applied for views.
If DEBUG is on, we serve the view without authenticating.
Default is 'django.contrib.auth.decorators.login_required'.
Can also be 'django.contrib.admin.views.decorators.staff_member_required'
or a custom decorator.
"""
AUTH = geta... | python | def secure(view):
"""Set an auth decorator applied for views.
If DEBUG is on, we serve the view without authenticating.
Default is 'django.contrib.auth.decorators.login_required'.
Can also be 'django.contrib.admin.views.decorators.staff_member_required'
or a custom decorator.
"""
AUTH = geta... | [
"def",
"secure",
"(",
"view",
")",
":",
"AUTH",
"=",
"getattr",
"(",
"settings",
",",
"'SLACKCHAT_AUTH_DECORATOR'",
",",
"'django.contrib.admin.views.decorators.staff_member_required'",
")",
"auth_decorator",
"=",
"import_class",
"(",
"AUTH",
")",
"return",
"method_deco... | Set an auth decorator applied for views.
If DEBUG is on, we serve the view without authenticating.
Default is 'django.contrib.auth.decorators.login_required'.
Can also be 'django.contrib.admin.views.decorators.staff_member_required'
or a custom decorator. | [
"Set",
"an",
"auth",
"decorator",
"applied",
"for",
"views",
".",
"If",
"DEBUG",
"is",
"on",
"we",
"serve",
"the",
"view",
"without",
"authenticating",
".",
"Default",
"is",
"django",
".",
"contrib",
".",
"auth",
".",
"decorators",
".",
"login_required",
"... | train | https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/authentication.py#L46-L59 |
intelligenia/modeltranslation | modeltranslation/views.py | import_translations | def import_translations(request, language):
"""
Importa las traducciones a partir de un archivo PO. Ten en cuenta
que el archivo PO ha de ser generado desde esta aplicación, de forma
que los comentarios sirvan como id de traducción (lo metemos nosotros
en la exportación).
"""
def _import_po_file(uploadedfile, la... | python | def import_translations(request, language):
"""
Importa las traducciones a partir de un archivo PO. Ten en cuenta
que el archivo PO ha de ser generado desde esta aplicación, de forma
que los comentarios sirvan como id de traducción (lo metemos nosotros
en la exportación).
"""
def _import_po_file(uploadedfile, la... | [
"def",
"import_translations",
"(",
"request",
",",
"language",
")",
":",
"def",
"_import_po_file",
"(",
"uploadedfile",
",",
"lang",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"uploadedfile",
":",
"lines",
".",
"append",
"(",
"line",
")",
"nu... | Importa las traducciones a partir de un archivo PO. Ten en cuenta
que el archivo PO ha de ser generado desde esta aplicación, de forma
que los comentarios sirvan como id de traducción (lo metemos nosotros
en la exportación). | [
"Importa",
"las",
"traducciones",
"a",
"partir",
"de",
"un",
"archivo",
"PO",
".",
"Ten",
"en",
"cuenta",
"que",
"el",
"archivo",
"PO",
"ha",
"de",
"ser",
"generado",
"desde",
"esta",
"aplicación",
"de",
"forma",
"que",
"los",
"comentarios",
"sirvan",
"com... | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/views.py#L117-L183 |
cloud-compose/cloud-compose-cluster | cloudcompose/cluster/commands/cli.py | up | def up(cloud_init, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time):
"""
creates a new cluster
"""
try:
cloud_config = CloudConfig()
ci = None
if cloud_init:
ci = CloudInit()
cloud_controller = CloudController(cloud_config)
cloud_contro... | python | def up(cloud_init, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time):
"""
creates a new cluster
"""
try:
cloud_config = CloudConfig()
ci = None
if cloud_init:
ci = CloudInit()
cloud_controller = CloudController(cloud_config)
cloud_contro... | [
"def",
"up",
"(",
"cloud_init",
",",
"use_snapshots",
",",
"upgrade_image",
",",
"snapshot_cluster",
",",
"snapshot_time",
")",
":",
"try",
":",
"cloud_config",
"=",
"CloudConfig",
"(",
")",
"ci",
"=",
"None",
"if",
"cloud_init",
":",
"ci",
"=",
"CloudInit",... | creates a new cluster | [
"creates",
"a",
"new",
"cluster"
] | train | https://github.com/cloud-compose/cloud-compose-cluster/blob/b6042419e778f3bf2257915def067972e5ce72cc/cloudcompose/cluster/commands/cli.py#L18-L32 |
cloud-compose/cloud-compose-cluster | cloudcompose/cluster/commands/cli.py | down | def down(force):
"""
destroys an existing cluster
"""
try:
cloud_config = CloudConfig()
cloud_controller = CloudController(cloud_config)
cloud_controller.down(force)
except CloudComposeException as ex:
print(ex) | python | def down(force):
"""
destroys an existing cluster
"""
try:
cloud_config = CloudConfig()
cloud_controller = CloudController(cloud_config)
cloud_controller.down(force)
except CloudComposeException as ex:
print(ex) | [
"def",
"down",
"(",
"force",
")",
":",
"try",
":",
"cloud_config",
"=",
"CloudConfig",
"(",
")",
"cloud_controller",
"=",
"CloudController",
"(",
"cloud_config",
")",
"cloud_controller",
".",
"down",
"(",
"force",
")",
"except",
"CloudComposeException",
"as",
... | destroys an existing cluster | [
"destroys",
"an",
"existing",
"cluster"
] | train | https://github.com/cloud-compose/cloud-compose-cluster/blob/b6042419e778f3bf2257915def067972e5ce72cc/cloudcompose/cluster/commands/cli.py#L36-L45 |
cloud-compose/cloud-compose-cluster | cloudcompose/cluster/commands/cli.py | cleanup | def cleanup():
"""
deletes launch configs and auto scaling group
"""
try:
cloud_config = CloudConfig()
cloud_controller = CloudController(cloud_config)
cloud_controller.cleanup()
except CloudComposeException as ex:
print(ex) | python | def cleanup():
"""
deletes launch configs and auto scaling group
"""
try:
cloud_config = CloudConfig()
cloud_controller = CloudController(cloud_config)
cloud_controller.cleanup()
except CloudComposeException as ex:
print(ex) | [
"def",
"cleanup",
"(",
")",
":",
"try",
":",
"cloud_config",
"=",
"CloudConfig",
"(",
")",
"cloud_controller",
"=",
"CloudController",
"(",
"cloud_config",
")",
"cloud_controller",
".",
"cleanup",
"(",
")",
"except",
"CloudComposeException",
"as",
"ex",
":",
"... | deletes launch configs and auto scaling group | [
"deletes",
"launch",
"configs",
"and",
"auto",
"scaling",
"group"
] | train | https://github.com/cloud-compose/cloud-compose-cluster/blob/b6042419e778f3bf2257915def067972e5ce72cc/cloudcompose/cluster/commands/cli.py#L48-L57 |
cloud-compose/cloud-compose-cluster | cloudcompose/cluster/commands/cli.py | build | def build():
"""
builds the cloud_init script
"""
try:
cloud_config = CloudConfig()
config_data = cloud_config.config_data('cluster')
cloud_init = CloudInit()
print(cloud_init.build(config_data))
except CloudComposeException as ex:
print(ex) | python | def build():
"""
builds the cloud_init script
"""
try:
cloud_config = CloudConfig()
config_data = cloud_config.config_data('cluster')
cloud_init = CloudInit()
print(cloud_init.build(config_data))
except CloudComposeException as ex:
print(ex) | [
"def",
"build",
"(",
")",
":",
"try",
":",
"cloud_config",
"=",
"CloudConfig",
"(",
")",
"config_data",
"=",
"cloud_config",
".",
"config_data",
"(",
"'cluster'",
")",
"cloud_init",
"=",
"CloudInit",
"(",
")",
"print",
"(",
"cloud_init",
".",
"build",
"(",... | builds the cloud_init script | [
"builds",
"the",
"cloud_init",
"script"
] | train | https://github.com/cloud-compose/cloud-compose-cluster/blob/b6042419e778f3bf2257915def067972e5ce72cc/cloudcompose/cluster/commands/cli.py#L60-L70 |
epandurski/flask_signalbus | flask_signalbus/signalbus_cli.py | flush | def flush(signal_names, exclude, wait):
"""Send pending signals over the message bus.
If a list of SIGNAL_NAMES is specified, flushes only those
signals. If no SIGNAL_NAMES are specified, flushes all signals.
"""
signalbus = current_app.extensions['signalbus']
signal_names = set(signal_names)... | python | def flush(signal_names, exclude, wait):
"""Send pending signals over the message bus.
If a list of SIGNAL_NAMES is specified, flushes only those
signals. If no SIGNAL_NAMES are specified, flushes all signals.
"""
signalbus = current_app.extensions['signalbus']
signal_names = set(signal_names)... | [
"def",
"flush",
"(",
"signal_names",
",",
"exclude",
",",
"wait",
")",
":",
"signalbus",
"=",
"current_app",
".",
"extensions",
"[",
"'signalbus'",
"]",
"signal_names",
"=",
"set",
"(",
"signal_names",
")",
"exclude",
"=",
"set",
"(",
"exclude",
")",
"mode... | Send pending signals over the message bus.
If a list of SIGNAL_NAMES is specified, flushes only those
signals. If no SIGNAL_NAMES are specified, flushes all signals. | [
"Send",
"pending",
"signals",
"over",
"the",
"message",
"bus",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus_cli.py#L21-L55 |
epandurski/flask_signalbus | flask_signalbus/signalbus_cli.py | flushmany | def flushmany():
"""Send a potentially huge number of pending signals over the message bus.
This command assumes that the number of pending signals might be
huge, so that they might not fit into memory. However, it is not
very smart in handling concurrent senders. It is mostly useful
when recoverin... | python | def flushmany():
"""Send a potentially huge number of pending signals over the message bus.
This command assumes that the number of pending signals might be
huge, so that they might not fit into memory. However, it is not
very smart in handling concurrent senders. It is mostly useful
when recoverin... | [
"def",
"flushmany",
"(",
")",
":",
"signalbus",
"=",
"current_app",
".",
"extensions",
"[",
"'signalbus'",
"]",
"signal_count",
"=",
"signalbus",
".",
"flushmany",
"(",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"signal_coun... | Send a potentially huge number of pending signals over the message bus.
This command assumes that the number of pending signals might be
huge, so that they might not fit into memory. However, it is not
very smart in handling concurrent senders. It is mostly useful
when recovering from long periods of d... | [
"Send",
"a",
"potentially",
"huge",
"number",
"of",
"pending",
"signals",
"over",
"the",
"message",
"bus",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus_cli.py#L60-L77 |
epandurski/flask_signalbus | flask_signalbus/signalbus_cli.py | signals | def signals():
"""Show all signal types."""
signalbus = current_app.extensions['signalbus']
for signal_model in signalbus.get_signal_models():
click.echo(signal_model.__name__) | python | def signals():
"""Show all signal types."""
signalbus = current_app.extensions['signalbus']
for signal_model in signalbus.get_signal_models():
click.echo(signal_model.__name__) | [
"def",
"signals",
"(",
")",
":",
"signalbus",
"=",
"current_app",
".",
"extensions",
"[",
"'signalbus'",
"]",
"for",
"signal_model",
"in",
"signalbus",
".",
"get_signal_models",
"(",
")",
":",
"click",
".",
"echo",
"(",
"signal_model",
".",
"__name__",
")"
] | Show all signal types. | [
"Show",
"all",
"signal",
"types",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus_cli.py#L82-L87 |
epandurski/flask_signalbus | flask_signalbus/signalbus_cli.py | pending | def pending():
"""Show the number of pending signals by signal type."""
signalbus = current_app.extensions['signalbus']
pending = []
total_pending = 0
for signal_model in signalbus.get_signal_models():
count = signal_model.query.count()
if count > 0:
pending.append((coun... | python | def pending():
"""Show the number of pending signals by signal type."""
signalbus = current_app.extensions['signalbus']
pending = []
total_pending = 0
for signal_model in signalbus.get_signal_models():
count = signal_model.query.count()
if count > 0:
pending.append((coun... | [
"def",
"pending",
"(",
")",
":",
"signalbus",
"=",
"current_app",
".",
"extensions",
"[",
"'signalbus'",
"]",
"pending",
"=",
"[",
"]",
"total_pending",
"=",
"0",
"for",
"signal_model",
"in",
"signalbus",
".",
"get_signal_models",
"(",
")",
":",
"count",
"... | Show the number of pending signals by signal type. | [
"Show",
"the",
"number",
"of",
"pending",
"signals",
"by",
"signal",
"type",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus_cli.py#L92-L109 |
intelligenia/modeltranslation | modeltranslation/transcache.py | TransCache._create_key | def _create_key(lang, instance):
"""Crea la clave única de la caché"""
model_name = instance.__class__.__name__
return "{0}__{1}_{2}".format(lang,model_name,instance.id) | python | def _create_key(lang, instance):
"""Crea la clave única de la caché"""
model_name = instance.__class__.__name__
return "{0}__{1}_{2}".format(lang,model_name,instance.id) | [
"def",
"_create_key",
"(",
"lang",
",",
"instance",
")",
":",
"model_name",
"=",
"instance",
".",
"__class__",
".",
"__name__",
"return",
"\"{0}__{1}_{2}\"",
".",
"format",
"(",
"lang",
",",
"model_name",
",",
"instance",
".",
"id",
")"
] | Crea la clave única de la caché | [
"Crea",
"la",
"clave",
"única",
"de",
"la",
"caché"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/transcache.py#L34-L37 |
intelligenia/modeltranslation | modeltranslation/transcache.py | TransCache._cache_is_expired | def _cache_is_expired():
"""Indica si la caché está caducada"""
now = timezone.now()
timediff = TransCache.SINGLETON_CREATION_DATETIME - now
return (timediff.total_seconds() > TransCache.SINGLETON_EXPIRATION_MAX_SECONDS) | python | def _cache_is_expired():
"""Indica si la caché está caducada"""
now = timezone.now()
timediff = TransCache.SINGLETON_CREATION_DATETIME - now
return (timediff.total_seconds() > TransCache.SINGLETON_EXPIRATION_MAX_SECONDS) | [
"def",
"_cache_is_expired",
"(",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"timediff",
"=",
"TransCache",
".",
"SINGLETON_CREATION_DATETIME",
"-",
"now",
"return",
"(",
"timediff",
".",
"total_seconds",
"(",
")",
">",
"TransCache",
".",
"SINGLE... | Indica si la caché está caducada | [
"Indica",
"si",
"la",
"caché",
"está",
"caducada"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/transcache.py#L40-L44 |
intelligenia/modeltranslation | modeltranslation/transcache.py | TransCache.factory | def factory():
"""Factoría del singleton, o crea una nueva o devuelve la existente"""
if not TransCache.SINGLETON or TransCache._cache_is_expired():
TransCache.SINGLETON = TransCache()
TransCache.SINGLETON_CREATION_DATETIME = timezone.now()
return TransCache.SINGLETON | python | def factory():
"""Factoría del singleton, o crea una nueva o devuelve la existente"""
if not TransCache.SINGLETON or TransCache._cache_is_expired():
TransCache.SINGLETON = TransCache()
TransCache.SINGLETON_CREATION_DATETIME = timezone.now()
return TransCache.SINGLETON | [
"def",
"factory",
"(",
")",
":",
"if",
"not",
"TransCache",
".",
"SINGLETON",
"or",
"TransCache",
".",
"_cache_is_expired",
"(",
")",
":",
"TransCache",
".",
"SINGLETON",
"=",
"TransCache",
"(",
")",
"TransCache",
".",
"SINGLETON_CREATION_DATETIME",
"=",
"time... | Factoría del singleton, o crea una nueva o devuelve la existente | [
"Factoría",
"del",
"singleton",
"o",
"crea",
"una",
"nueva",
"o",
"devuelve",
"la",
"existente"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/transcache.py#L55-L61 |
intelligenia/modeltranslation | modeltranslation/transcache.py | TransCache.set | def set(self, lang, instance):
"""
Establece en la instancia actual los atributos de traducción
y la almacena en un diccionario de claves _create_key y valores
el objeto con los atributos dinámicos.
"""
if self._cache_is_too_big():
self.cache = {}
inst... | python | def set(self, lang, instance):
"""
Establece en la instancia actual los atributos de traducción
y la almacena en un diccionario de claves _create_key y valores
el objeto con los atributos dinámicos.
"""
if self._cache_is_too_big():
self.cache = {}
inst... | [
"def",
"set",
"(",
"self",
",",
"lang",
",",
"instance",
")",
":",
"if",
"self",
".",
"_cache_is_too_big",
"(",
")",
":",
"self",
".",
"cache",
"=",
"{",
"}",
"instance_key",
"=",
"TransCache",
".",
"_create_key",
"(",
"lang",
",",
"instance",
")",
"... | Establece en la instancia actual los atributos de traducción
y la almacena en un diccionario de claves _create_key y valores
el objeto con los atributos dinámicos. | [
"Establece",
"en",
"la",
"instancia",
"actual",
"los",
"atributos",
"de",
"traducción",
"y",
"la",
"almacena",
"en",
"un",
"diccionario",
"de",
"claves",
"_create_key",
"y",
"valores",
"el",
"objeto",
"con",
"los",
"atributos",
"dinámicos",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/transcache.py#L68-L79 |
intelligenia/modeltranslation | modeltranslation/transcache.py | TransCache.has | def has(self, lang, instance):
"""
Indica si la caché tiene un objeto igual a éste con los
atributos dinámicos de traducción
"""
instance_key = TransCache._create_key(lang, instance)
return instance_key in self.cache | python | def has(self, lang, instance):
"""
Indica si la caché tiene un objeto igual a éste con los
atributos dinámicos de traducción
"""
instance_key = TransCache._create_key(lang, instance)
return instance_key in self.cache | [
"def",
"has",
"(",
"self",
",",
"lang",
",",
"instance",
")",
":",
"instance_key",
"=",
"TransCache",
".",
"_create_key",
"(",
"lang",
",",
"instance",
")",
"return",
"instance_key",
"in",
"self",
".",
"cache"
] | Indica si la caché tiene un objeto igual a éste con los
atributos dinámicos de traducción | [
"Indica",
"si",
"la",
"caché",
"tiene",
"un",
"objeto",
"igual",
"a",
"éste",
"con",
"los",
"atributos",
"dinámicos",
"de",
"traducción"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/transcache.py#L81-L87 |
intelligenia/modeltranslation | modeltranslation/transcache.py | TransCache.get | def get(self, lang, instance):
"""
Obtiene una instancia igual a ésta, pero con los atributos
dinámicos de traduccción
"""
instance_key = TransCache._create_key(lang, instance)
return self.cache[instance_key] | python | def get(self, lang, instance):
"""
Obtiene una instancia igual a ésta, pero con los atributos
dinámicos de traduccción
"""
instance_key = TransCache._create_key(lang, instance)
return self.cache[instance_key] | [
"def",
"get",
"(",
"self",
",",
"lang",
",",
"instance",
")",
":",
"instance_key",
"=",
"TransCache",
".",
"_create_key",
"(",
"lang",
",",
"instance",
")",
"return",
"self",
".",
"cache",
"[",
"instance_key",
"]"
] | Obtiene una instancia igual a ésta, pero con los atributos
dinámicos de traduccción | [
"Obtiene",
"una",
"instancia",
"igual",
"a",
"ésta",
"pero",
"con",
"los",
"atributos",
"dinámicos",
"de",
"traduccción"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/transcache.py#L89-L95 |
inveniosoftware/invenio-iiif | invenio_iiif/tasks.py | create_thumbnail | def create_thumbnail(uuid, thumbnail_width):
"""Create the thumbnail for an image."""
# size = '!' + thumbnail_width + ','
size = thumbnail_width + ',' # flask_iiif doesn't support ! at the moment
thumbnail = IIIFImageAPI.get('v2', uuid, size, 0, 'default', 'jpg') | python | def create_thumbnail(uuid, thumbnail_width):
"""Create the thumbnail for an image."""
# size = '!' + thumbnail_width + ','
size = thumbnail_width + ',' # flask_iiif doesn't support ! at the moment
thumbnail = IIIFImageAPI.get('v2', uuid, size, 0, 'default', 'jpg') | [
"def",
"create_thumbnail",
"(",
"uuid",
",",
"thumbnail_width",
")",
":",
"# size = '!' + thumbnail_width + ','",
"size",
"=",
"thumbnail_width",
"+",
"','",
"# flask_iiif doesn't support ! at the moment",
"thumbnail",
"=",
"IIIFImageAPI",
".",
"get",
"(",
"'v2'",
",",
... | Create the thumbnail for an image. | [
"Create",
"the",
"thumbnail",
"for",
"an",
"image",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/tasks.py#L18-L22 |
kserhii/money-parser | money_parser/__init__.py | price_str | def price_str(raw_price, default=_not_defined, dec_point='.'):
"""Search and clean price value.
Convert raw price string presented in any localization
as a valid number string with an optional decimal point.
If raw price does not contain valid price value or contains
more than one price value, the... | python | def price_str(raw_price, default=_not_defined, dec_point='.'):
"""Search and clean price value.
Convert raw price string presented in any localization
as a valid number string with an optional decimal point.
If raw price does not contain valid price value or contains
more than one price value, the... | [
"def",
"price_str",
"(",
"raw_price",
",",
"default",
"=",
"_not_defined",
",",
"dec_point",
"=",
"'.'",
")",
":",
"def",
"_error_or_default",
"(",
"err_msg",
")",
":",
"if",
"default",
"==",
"_not_defined",
":",
"raise",
"ValueError",
"(",
"err_msg",
")",
... | Search and clean price value.
Convert raw price string presented in any localization
as a valid number string with an optional decimal point.
If raw price does not contain valid price value or contains
more than one price value, then return default value.
If default value not set, then raise Value... | [
"Search",
"and",
"clean",
"price",
"value",
"."
] | train | https://github.com/kserhii/money-parser/blob/d02da58eb3065c55b73c9a7e601ffb3e1448bcd1/money_parser/__init__.py#L15-L101 |
kserhii/money-parser | money_parser/__init__.py | price_dec | def price_dec(raw_price, default=_not_defined):
"""Price decimal value from raw string.
Extract price value from input raw string and
present as Decimal number.
If raw price does not contain valid price value or contains
more than one price value, then return default value.
If default value no... | python | def price_dec(raw_price, default=_not_defined):
"""Price decimal value from raw string.
Extract price value from input raw string and
present as Decimal number.
If raw price does not contain valid price value or contains
more than one price value, then return default value.
If default value no... | [
"def",
"price_dec",
"(",
"raw_price",
",",
"default",
"=",
"_not_defined",
")",
":",
"try",
":",
"price",
"=",
"price_str",
"(",
"raw_price",
")",
"return",
"decimal",
".",
"Decimal",
"(",
"price",
")",
"except",
"ValueError",
"as",
"err",
":",
"if",
"de... | Price decimal value from raw string.
Extract price value from input raw string and
present as Decimal number.
If raw price does not contain valid price value or contains
more than one price value, then return default value.
If default value not set, then raise ValueError.
:param str raw_price... | [
"Price",
"decimal",
"value",
"from",
"raw",
"string",
"."
] | train | https://github.com/kserhii/money-parser/blob/d02da58eb3065c55b73c9a7e601ffb3e1448bcd1/money_parser/__init__.py#L104-L127 |
ericholscher/django-kong | kong/views.py | flotify | def flotify(result, num=50):
"""
Return a list of (timestamp, duration) sets for test result.
"""
results = list(TestResult.objects.filter(test=result.test, site=result.site)[:num])
results.reverse()
return [[get_timestamp(result.run_date), result.duration/1000] for result in results] | python | def flotify(result, num=50):
"""
Return a list of (timestamp, duration) sets for test result.
"""
results = list(TestResult.objects.filter(test=result.test, site=result.site)[:num])
results.reverse()
return [[get_timestamp(result.run_date), result.duration/1000] for result in results] | [
"def",
"flotify",
"(",
"result",
",",
"num",
"=",
"50",
")",
":",
"results",
"=",
"list",
"(",
"TestResult",
".",
"objects",
".",
"filter",
"(",
"test",
"=",
"result",
".",
"test",
",",
"site",
"=",
"result",
".",
"site",
")",
"[",
":",
"num",
"]... | Return a list of (timestamp, duration) sets for test result. | [
"Return",
"a",
"list",
"of",
"(",
"timestamp",
"duration",
")",
"sets",
"for",
"test",
"result",
"."
] | train | https://github.com/ericholscher/django-kong/blob/02e1bc4332739387adc1d7b2f4aeadd7f7db896f/kong/views.py#L38-L44 |
ericholscher/django-kong | kong/plugins/munin.py | Plugin.__get_dynamic_attr | def __get_dynamic_attr(self, attname, arg, default=None):
"""
Gets "something" from self, which could be an attribute or
a callable with either 0 or 1 arguments (besides self).
Stolen from django.contrib.syntication.feeds.Feed.
"""
try:
attr = getattr... | python | def __get_dynamic_attr(self, attname, arg, default=None):
"""
Gets "something" from self, which could be an attribute or
a callable with either 0 or 1 arguments (besides self).
Stolen from django.contrib.syntication.feeds.Feed.
"""
try:
attr = getattr... | [
"def",
"__get_dynamic_attr",
"(",
"self",
",",
"attname",
",",
"arg",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"attr",
"=",
"getattr",
"(",
"self",
",",
"attname",
")",
"except",
"AttributeError",
":",
"return",
"default",
"if",
"callable",
"("... | Gets "something" from self, which could be an attribute or
a callable with either 0 or 1 arguments (besides self).
Stolen from django.contrib.syntication.feeds.Feed. | [
"Gets",
"something",
"from",
"self",
"which",
"could",
"be",
"an",
"attribute",
"or",
"a",
"callable",
"with",
"either",
"0",
"or",
"1",
"arguments",
"(",
"besides",
"self",
")",
".",
"Stolen",
"from",
"django",
".",
"contrib",
".",
"syntication",
".",
"... | train | https://github.com/ericholscher/django-kong/blob/02e1bc4332739387adc1d7b2f4aeadd7f7db896f/kong/plugins/munin.py#L55-L79 |
paksu/pytelegraf | telegraf/client.py | ClientBase.metric | def metric(self, measurement_name, values, tags=None, timestamp=None):
"""
Append global tags configured for the client to the tags given then
converts the data into InfluxDB Line protocol and sends to to socket
"""
if not measurement_name or values in (None, {}):
# D... | python | def metric(self, measurement_name, values, tags=None, timestamp=None):
"""
Append global tags configured for the client to the tags given then
converts the data into InfluxDB Line protocol and sends to to socket
"""
if not measurement_name or values in (None, {}):
# D... | [
"def",
"metric",
"(",
"self",
",",
"measurement_name",
",",
"values",
",",
"tags",
"=",
"None",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"not",
"measurement_name",
"or",
"values",
"in",
"(",
"None",
",",
"{",
"}",
")",
":",
"# Don't try to send emp... | Append global tags configured for the client to the tags given then
converts the data into InfluxDB Line protocol and sends to to socket | [
"Append",
"global",
"tags",
"configured",
"for",
"the",
"client",
"to",
"the",
"tags",
"given",
"then",
"converts",
"the",
"data",
"into",
"InfluxDB",
"Line",
"protocol",
"and",
"sends",
"to",
"to",
"socket"
] | train | https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/client.py#L13-L29 |
paksu/pytelegraf | telegraf/client.py | TelegrafClient.send | def send(self, data):
"""
Sends the given data to the socket via UDP
"""
try:
self.socket.sendto(data.encode('utf8') + b'\n', (self.host, self.port))
except (socket.error, RuntimeError):
# Socket errors should fail silently so they don't affect anything el... | python | def send(self, data):
"""
Sends the given data to the socket via UDP
"""
try:
self.socket.sendto(data.encode('utf8') + b'\n', (self.host, self.port))
except (socket.error, RuntimeError):
# Socket errors should fail silently so they don't affect anything el... | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"self",
".",
"socket",
".",
"sendto",
"(",
"data",
".",
"encode",
"(",
"'utf8'",
")",
"+",
"b'\\n'",
",",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
")",
"except",
"("... | Sends the given data to the socket via UDP | [
"Sends",
"the",
"given",
"data",
"to",
"the",
"socket",
"via",
"UDP"
] | train | https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/client.py#L44-L52 |
paksu/pytelegraf | telegraf/client.py | HttpClient.send | def send(self, data):
"""
Send the data in a separate thread via HTTP POST.
HTTP introduces some overhead, so to avoid blocking the main thread,
this issues the request in the background.
"""
self.future_session.post(url=self.url, data=data) | python | def send(self, data):
"""
Send the data in a separate thread via HTTP POST.
HTTP introduces some overhead, so to avoid blocking the main thread,
this issues the request in the background.
"""
self.future_session.post(url=self.url, data=data) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"future_session",
".",
"post",
"(",
"url",
"=",
"self",
".",
"url",
",",
"data",
"=",
"data",
")"
] | Send the data in a separate thread via HTTP POST.
HTTP introduces some overhead, so to avoid blocking the main thread,
this issues the request in the background. | [
"Send",
"the",
"data",
"in",
"a",
"separate",
"thread",
"via",
"HTTP",
"POST",
".",
"HTTP",
"introduces",
"some",
"overhead",
"so",
"to",
"avoid",
"blocking",
"the",
"main",
"thread",
"this",
"issues",
"the",
"request",
"in",
"the",
"background",
"."
] | train | https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/client.py#L73-L79 |
paksu/pytelegraf | telegraf/protocol.py | Line.get_output_values | def get_output_values(self):
"""
Return an escaped string of comma separated value_name: value pairs
"""
# Handle primitive values here and implicitly convert them to a dict because
# it allows the API to be simpler.
# Also influxDB mandates that each value also has a na... | python | def get_output_values(self):
"""
Return an escaped string of comma separated value_name: value pairs
"""
# Handle primitive values here and implicitly convert them to a dict because
# it allows the API to be simpler.
# Also influxDB mandates that each value also has a na... | [
"def",
"get_output_values",
"(",
"self",
")",
":",
"# Handle primitive values here and implicitly convert them to a dict because",
"# it allows the API to be simpler.",
"# Also influxDB mandates that each value also has a name so the default name",
"# for any non-dict value is \"value\"",
"if",
... | Return an escaped string of comma separated value_name: value pairs | [
"Return",
"an",
"escaped",
"string",
"of",
"comma",
"separated",
"value_name",
":",
"value",
"pairs"
] | train | https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/protocol.py#L24-L44 |
paksu/pytelegraf | telegraf/protocol.py | Line.get_output_tags | def get_output_tags(self):
"""
Return an escaped string of comma separated tag_name: tag_value pairs
Tags should be sorted by key before being sent for best performance. The sort should
match that from the Go bytes. Compare function (http://golang.org/pkg/bytes/#Compare).
"""
... | python | def get_output_tags(self):
"""
Return an escaped string of comma separated tag_name: tag_value pairs
Tags should be sorted by key before being sent for best performance. The sort should
match that from the Go bytes. Compare function (http://golang.org/pkg/bytes/#Compare).
"""
... | [
"def",
"get_output_tags",
"(",
"self",
")",
":",
"# Sort the tags in lexicographically by tag name",
"sorted_tags",
"=",
"sorted",
"(",
"self",
".",
"tags",
".",
"items",
"(",
")",
")",
"# Finally render, escape and return the tag string",
"return",
"u\",\"",
".",
"join... | Return an escaped string of comma separated tag_name: tag_value pairs
Tags should be sorted by key before being sent for best performance. The sort should
match that from the Go bytes. Compare function (http://golang.org/pkg/bytes/#Compare). | [
"Return",
"an",
"escaped",
"string",
"of",
"comma",
"separated",
"tag_name",
":",
"tag_value",
"pairs"
] | train | https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/protocol.py#L46-L58 |
paksu/pytelegraf | telegraf/protocol.py | Line.to_line_protocol | def to_line_protocol(self):
"""
Converts the given metrics as a single line of InfluxDB line protocol
"""
tags = self.get_output_tags()
return u"{0}{1} {2}{3}".format(
self.get_output_measurement(),
"," + tags if tags else '',
self.get_output_... | python | def to_line_protocol(self):
"""
Converts the given metrics as a single line of InfluxDB line protocol
"""
tags = self.get_output_tags()
return u"{0}{1} {2}{3}".format(
self.get_output_measurement(),
"," + tags if tags else '',
self.get_output_... | [
"def",
"to_line_protocol",
"(",
"self",
")",
":",
"tags",
"=",
"self",
".",
"get_output_tags",
"(",
")",
"return",
"u\"{0}{1} {2}{3}\"",
".",
"format",
"(",
"self",
".",
"get_output_measurement",
"(",
")",
",",
"\",\"",
"+",
"tags",
"if",
"tags",
"else",
"... | Converts the given metrics as a single line of InfluxDB line protocol | [
"Converts",
"the",
"given",
"metrics",
"as",
"a",
"single",
"line",
"of",
"InfluxDB",
"line",
"protocol"
] | train | https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/protocol.py#L66-L77 |
paksu/pytelegraf | telegraf/utils.py | format_string | def format_string(key):
"""
Formats either measurement names, tag names or tag values.
Measurement name and any optional tags separated by commas. Measurement names, tag keys,
and tag values must escape any spaces, commas or equal signs using a backslash (\).
For example: \ and \,.
All tag val... | python | def format_string(key):
"""
Formats either measurement names, tag names or tag values.
Measurement name and any optional tags separated by commas. Measurement names, tag keys,
and tag values must escape any spaces, commas or equal signs using a backslash (\).
For example: \ and \,.
All tag val... | [
"def",
"format_string",
"(",
"key",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"basestring",
")",
":",
"key",
"=",
"key",
".",
"replace",
"(",
"\",\"",
",",
"\"\\,\"",
")",
"key",
"=",
"key",
".",
"replace",
"(",
"\" \"",
",",
"\"\\ \"",
")",
"... | Formats either measurement names, tag names or tag values.
Measurement name and any optional tags separated by commas. Measurement names, tag keys,
and tag values must escape any spaces, commas or equal signs using a backslash (\).
For example: \ and \,.
All tag values are stored as strings and should... | [
"Formats",
"either",
"measurement",
"names",
"tag",
"names",
"or",
"tag",
"values",
"."
] | train | https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/utils.py#L8-L22 |
paksu/pytelegraf | telegraf/utils.py | format_value | def format_value(value):
"""
Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted
(e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i.
If they do not they will be written as floats.
Floats are numeric values that are not foll... | python | def format_value(value):
"""
Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted
(e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i.
If they do not they will be written as floats.
Floats are numeric values that are not foll... | [
"def",
"format_value",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"'\"'",
",",
"'\\\"'",
")",
"value",
"=",
"u'\"{0}\"'",
".",
"format",
"(",
"value",
")",
"elif",
... | Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted
(e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i.
If they do not they will be written as floats.
Floats are numeric values that are not followed by a trailing i. (e.g. 1, 1.0, -... | [
"Integers",
"are",
"numeric",
"values",
"that",
"do",
"not",
"include",
"a",
"decimal",
"and",
"are",
"followed",
"by",
"a",
"trailing",
"i",
"when",
"inserted",
"(",
"e",
".",
"g",
".",
"1i",
"345i",
"2015i",
"-",
"10i",
")",
".",
"Note",
"that",
"a... | train | https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/utils.py#L25-L48 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.