repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
brutasse/django-password-reset | password_reset/views.py | loads_with_timestamp | def loads_with_timestamp(value, salt):
"""Returns the unsigned value along with its timestamp, the time when it
got dumped."""
try:
signing.loads(value, salt=salt, max_age=-999999)
except signing.SignatureExpired as e:
age = float(str(e).split('Signature age ')[1].split(' >')[0])
timestamp = timezone.now() - datetime.timedelta(seconds=age)
return timestamp, signing.loads(value, salt=salt) | python | def loads_with_timestamp(value, salt):
"""Returns the unsigned value along with its timestamp, the time when it
got dumped."""
try:
signing.loads(value, salt=salt, max_age=-999999)
except signing.SignatureExpired as e:
age = float(str(e).split('Signature age ')[1].split(' >')[0])
timestamp = timezone.now() - datetime.timedelta(seconds=age)
return timestamp, signing.loads(value, salt=salt) | [
"def",
"loads_with_timestamp",
"(",
"value",
",",
"salt",
")",
":",
"try",
":",
"signing",
".",
"loads",
"(",
"value",
",",
"salt",
"=",
"salt",
",",
"max_age",
"=",
"-",
"999999",
")",
"except",
"signing",
".",
"SignatureExpired",
"as",
"e",
":",
"age... | Returns the unsigned value along with its timestamp, the time when it
got dumped. | [
"Returns",
"the",
"unsigned",
"value",
"along",
"with",
"its",
"timestamp",
"the",
"time",
"when",
"it",
"got",
"dumped",
"."
] | 3f3a531d8bbd7e456af214757afccdf06b0d12d1 | https://github.com/brutasse/django-password-reset/blob/3f3a531d8bbd7e456af214757afccdf06b0d12d1/password_reset/views.py#L27-L35 | train | 49,700 |
socialwifi/RouterOS-api | routeros_api/api_socket.py | set_keepalive | def set_keepalive(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
"""Set TCP keepalive on an open socket.
It activates after 1 second (after_idle_sec) of idleness,
then sends a keepalive ping once every 3 seconds (interval_sec),
and closes the connection after 5 failed ping (max_fails), or 15 seconds
"""
if hasattr(socket, "SO_KEEPALIVE"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if hasattr(socket, "TCP_KEEPIDLE"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
if hasattr(socket, "TCP_KEEPINTVL"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
if hasattr(socket, "TCP_KEEPCNT"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails) | python | def set_keepalive(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
"""Set TCP keepalive on an open socket.
It activates after 1 second (after_idle_sec) of idleness,
then sends a keepalive ping once every 3 seconds (interval_sec),
and closes the connection after 5 failed ping (max_fails), or 15 seconds
"""
if hasattr(socket, "SO_KEEPALIVE"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if hasattr(socket, "TCP_KEEPIDLE"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
if hasattr(socket, "TCP_KEEPINTVL"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
if hasattr(socket, "TCP_KEEPCNT"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails) | [
"def",
"set_keepalive",
"(",
"sock",
",",
"after_idle_sec",
"=",
"1",
",",
"interval_sec",
"=",
"3",
",",
"max_fails",
"=",
"5",
")",
":",
"if",
"hasattr",
"(",
"socket",
",",
"\"SO_KEEPALIVE\"",
")",
":",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
... | Set TCP keepalive on an open socket.
It activates after 1 second (after_idle_sec) of idleness,
then sends a keepalive ping once every 3 seconds (interval_sec),
and closes the connection after 5 failed ping (max_fails), or 15 seconds | [
"Set",
"TCP",
"keepalive",
"on",
"an",
"open",
"socket",
"."
] | d4eb2422f2437b3c99193a79fa857fc1e2c672af | https://github.com/socialwifi/RouterOS-api/blob/d4eb2422f2437b3c99193a79fa857fc1e2c672af/routeros_api/api_socket.py#L37-L51 | train | 49,701 |
thespacedoctor/sherlock | sherlock/imports/veron.py | veron._create_dictionary_of_veron | def _create_dictionary_of_veron(
self):
"""create a list of dictionaries containing all the rows in the veron catalogue
**Return:**
- ``dictList`` - a list of dictionaries containing all the rows in the veron catalogue
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring
"""
self.log.debug(
'starting the ``_create_dictionary_of_veron`` method')
dictList = []
lines = string.split(self.catData, '\n')
totalCount = len(lines)
count = 0
switch = 0
for line in lines:
if (len(line) == 0 or line[0] in ["#", " "]) and switch == 0:
continue
else:
switch = 1
count += 1
if count > 1:
# Cursor up one line and clear line
sys.stdout.write("\x1b[1A\x1b[2K")
print "%(count)s / %(totalCount)s veron data added to memory" % locals()
if count == 1:
theseKeys = []
someKeys = string.split(line, '|')
for key in someKeys:
if key == "_RAJ2000":
key = "raDeg"
if key == "_DEJ2000":
key = "decDeg"
if key == "Cl":
key = "class"
if key == "nR":
key = "not_radio"
if key == "Name":
key = "name"
if key == "l_z":
key = "redshift_flag"
if key == "z":
key = "redshift"
if key == "Sp":
key = "spectral_classification"
if key == "n_Vmag":
key = "magnitude_filter"
if key == "Vmag":
key = "magnitude"
if key == "B-V":
key = "B_V"
if key == "U-B":
key = "U_B"
if key == "Mabs":
key = "abs_magnitude"
theseKeys.append(key)
continue
if count in [2, 3]:
continue
thisDict = {}
theseValues = string.split(line, '|')
for k, v in zip(theseKeys, theseValues):
v = v.strip()
if len(v) == 0 or v == "-":
v = None
thisDict[k] = v
dictList.append(thisDict)
self.log.debug(
'completed the ``_create_dictionary_of_veron`` method')
return dictList | python | def _create_dictionary_of_veron(
self):
"""create a list of dictionaries containing all the rows in the veron catalogue
**Return:**
- ``dictList`` - a list of dictionaries containing all the rows in the veron catalogue
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring
"""
self.log.debug(
'starting the ``_create_dictionary_of_veron`` method')
dictList = []
lines = string.split(self.catData, '\n')
totalCount = len(lines)
count = 0
switch = 0
for line in lines:
if (len(line) == 0 or line[0] in ["#", " "]) and switch == 0:
continue
else:
switch = 1
count += 1
if count > 1:
# Cursor up one line and clear line
sys.stdout.write("\x1b[1A\x1b[2K")
print "%(count)s / %(totalCount)s veron data added to memory" % locals()
if count == 1:
theseKeys = []
someKeys = string.split(line, '|')
for key in someKeys:
if key == "_RAJ2000":
key = "raDeg"
if key == "_DEJ2000":
key = "decDeg"
if key == "Cl":
key = "class"
if key == "nR":
key = "not_radio"
if key == "Name":
key = "name"
if key == "l_z":
key = "redshift_flag"
if key == "z":
key = "redshift"
if key == "Sp":
key = "spectral_classification"
if key == "n_Vmag":
key = "magnitude_filter"
if key == "Vmag":
key = "magnitude"
if key == "B-V":
key = "B_V"
if key == "U-B":
key = "U_B"
if key == "Mabs":
key = "abs_magnitude"
theseKeys.append(key)
continue
if count in [2, 3]:
continue
thisDict = {}
theseValues = string.split(line, '|')
for k, v in zip(theseKeys, theseValues):
v = v.strip()
if len(v) == 0 or v == "-":
v = None
thisDict[k] = v
dictList.append(thisDict)
self.log.debug(
'completed the ``_create_dictionary_of_veron`` method')
return dictList | [
"def",
"_create_dictionary_of_veron",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_create_dictionary_of_veron`` method'",
")",
"dictList",
"=",
"[",
"]",
"lines",
"=",
"string",
".",
"split",
"(",
"self",
".",
"catData",
",",
... | create a list of dictionaries containing all the rows in the veron catalogue
**Return:**
- ``dictList`` - a list of dictionaries containing all the rows in the veron catalogue
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring | [
"create",
"a",
"list",
"of",
"dictionaries",
"containing",
"all",
"the",
"rows",
"in",
"the",
"veron",
"catalogue"
] | 2c80fb6fa31b04e7820e6928e3d437a21e692dd3 | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/imports/veron.py#L123-L208 | train | 49,702 |
andrewda/frc-livescore | livescore/simpleocr_utils/segmentation_filters.py | Filter.display | def display(self, display_before=False):
"""shows the effect of this filter"""
try:
copy = self.image.copy()
except AttributeError:
raise Exception("You need to set the Filter.image attribute for displaying")
copy = BrightnessProcessor(brightness=0.6).process(copy)
s, g = self._input, self.good_segments_indexes
draw_segments(copy, s[g], (0, 255, 0))
draw_segments(copy, s[True ^ g], (0, 0, 255))
show_image_and_wait_for_key(copy, "segments filtered by " + self.__class__.__name__) | python | def display(self, display_before=False):
"""shows the effect of this filter"""
try:
copy = self.image.copy()
except AttributeError:
raise Exception("You need to set the Filter.image attribute for displaying")
copy = BrightnessProcessor(brightness=0.6).process(copy)
s, g = self._input, self.good_segments_indexes
draw_segments(copy, s[g], (0, 255, 0))
draw_segments(copy, s[True ^ g], (0, 0, 255))
show_image_and_wait_for_key(copy, "segments filtered by " + self.__class__.__name__) | [
"def",
"display",
"(",
"self",
",",
"display_before",
"=",
"False",
")",
":",
"try",
":",
"copy",
"=",
"self",
".",
"image",
".",
"copy",
"(",
")",
"except",
"AttributeError",
":",
"raise",
"Exception",
"(",
"\"You need to set the Filter.image attribute for disp... | shows the effect of this filter | [
"shows",
"the",
"effect",
"of",
"this",
"filter"
] | 71594cd6d2c8b6c5feb3889bb05552d09b8128b1 | https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/segmentation_filters.py#L18-L28 | train | 49,703 |
Clinical-Genomics/trailblazer | trailblazer/mip/trending.py | parse_mip_analysis | def parse_mip_analysis(mip_config_raw: dict, qcmetrics_raw: dict, sampleinfo_raw: dict) -> dict:
"""Parse the output analysis files from MIP for adding info
to trend database
Args:
mip_config_raw (dict): raw YAML input from MIP analysis config file
qcmetrics_raw (dict): raw YAML input from MIP analysis qc metric file
sampleinfo_raw (dict): raw YAML input from MIP analysis qc sample info file
Returns:
dict: parsed data
"""
outdata = _define_output_dict()
_config(mip_config_raw, outdata)
_qc_metrics(outdata, qcmetrics_raw)
_qc_sample_info(outdata, sampleinfo_raw)
return outdata | python | def parse_mip_analysis(mip_config_raw: dict, qcmetrics_raw: dict, sampleinfo_raw: dict) -> dict:
"""Parse the output analysis files from MIP for adding info
to trend database
Args:
mip_config_raw (dict): raw YAML input from MIP analysis config file
qcmetrics_raw (dict): raw YAML input from MIP analysis qc metric file
sampleinfo_raw (dict): raw YAML input from MIP analysis qc sample info file
Returns:
dict: parsed data
"""
outdata = _define_output_dict()
_config(mip_config_raw, outdata)
_qc_metrics(outdata, qcmetrics_raw)
_qc_sample_info(outdata, sampleinfo_raw)
return outdata | [
"def",
"parse_mip_analysis",
"(",
"mip_config_raw",
":",
"dict",
",",
"qcmetrics_raw",
":",
"dict",
",",
"sampleinfo_raw",
":",
"dict",
")",
"->",
"dict",
":",
"outdata",
"=",
"_define_output_dict",
"(",
")",
"_config",
"(",
"mip_config_raw",
",",
"outdata",
"... | Parse the output analysis files from MIP for adding info
to trend database
Args:
mip_config_raw (dict): raw YAML input from MIP analysis config file
qcmetrics_raw (dict): raw YAML input from MIP analysis qc metric file
sampleinfo_raw (dict): raw YAML input from MIP analysis qc sample info file
Returns:
dict: parsed data | [
"Parse",
"the",
"output",
"analysis",
"files",
"from",
"MIP",
"for",
"adding",
"info",
"to",
"trend",
"database"
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/trending.py#L7-L24 | train | 49,704 |
thespacedoctor/sherlock | sherlock/database_cleaner.py | database_cleaner._updated_row_counts_in_tcs_helper_catalogue_tables_info | def _updated_row_counts_in_tcs_helper_catalogue_tables_info(
self):
""" updated row counts in tcs catalogue tables
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring
"""
self.log.debug(
'starting the ``_updated_row_counts_in_tcs_helper_catalogue_tables_info`` method')
sqlQuery = u"""
select * from tcs_helper_catalogue_tables_info where table_name like "%%stream" or (number_of_rows is null and legacy_table = 0)
""" % locals()
rows = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
for row in rows:
tbName = row["table_name"]
sqlQuery = u"""
update tcs_helper_catalogue_tables_info set number_of_rows = (select count(*) as count from %(tbName)s) where table_name = "%(tbName)s"
""" % locals()
writequery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
)
sqlQuery = u"""
select * from tcs_helper_catalogue_views_info where (number_of_rows is null and legacy_view = 0)
""" % locals()
rows = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
for row in rows:
tbName = row["view_name"]
print tbName
sqlQuery = u"""
update tcs_helper_catalogue_views_info set number_of_rows = (select count(*) as count from %(tbName)s) where view_name = "%(tbName)s"
""" % locals()
writequery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
)
self.log.debug(
'completed the ``_updated_row_counts_in_tcs_helper_catalogue_tables_info`` method')
return None | python | def _updated_row_counts_in_tcs_helper_catalogue_tables_info(
self):
""" updated row counts in tcs catalogue tables
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring
"""
self.log.debug(
'starting the ``_updated_row_counts_in_tcs_helper_catalogue_tables_info`` method')
sqlQuery = u"""
select * from tcs_helper_catalogue_tables_info where table_name like "%%stream" or (number_of_rows is null and legacy_table = 0)
""" % locals()
rows = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
for row in rows:
tbName = row["table_name"]
sqlQuery = u"""
update tcs_helper_catalogue_tables_info set number_of_rows = (select count(*) as count from %(tbName)s) where table_name = "%(tbName)s"
""" % locals()
writequery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
)
sqlQuery = u"""
select * from tcs_helper_catalogue_views_info where (number_of_rows is null and legacy_view = 0)
""" % locals()
rows = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
for row in rows:
tbName = row["view_name"]
print tbName
sqlQuery = u"""
update tcs_helper_catalogue_views_info set number_of_rows = (select count(*) as count from %(tbName)s) where view_name = "%(tbName)s"
""" % locals()
writequery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
)
self.log.debug(
'completed the ``_updated_row_counts_in_tcs_helper_catalogue_tables_info`` method')
return None | [
"def",
"_updated_row_counts_in_tcs_helper_catalogue_tables_info",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_updated_row_counts_in_tcs_helper_catalogue_tables_info`` method'",
")",
"sqlQuery",
"=",
"u\"\"\"\n select * from tcs_helper_ca... | updated row counts in tcs catalogue tables
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring | [
"updated",
"row",
"counts",
"in",
"tcs",
"catalogue",
"tables"
] | 2c80fb6fa31b04e7820e6928e3d437a21e692dd3 | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/database_cleaner.py#L113-L177 | train | 49,705 |
pytroll/posttroll | posttroll/listener.py | ListenerContainer.restart_listener | def restart_listener(self, topics):
'''Restart listener after configuration update.
'''
if self.listener is not None:
if self.listener.running:
self.stop()
self.__init__(topics=topics) | python | def restart_listener(self, topics):
'''Restart listener after configuration update.
'''
if self.listener is not None:
if self.listener.running:
self.stop()
self.__init__(topics=topics) | [
"def",
"restart_listener",
"(",
"self",
",",
"topics",
")",
":",
"if",
"self",
".",
"listener",
"is",
"not",
"None",
":",
"if",
"self",
".",
"listener",
".",
"running",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"__init__",
"(",
"topics",
"=",
... | Restart listener after configuration update. | [
"Restart",
"listener",
"after",
"configuration",
"update",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/listener.py#L65-L71 | train | 49,706 |
pytroll/posttroll | posttroll/listener.py | ListenerContainer.stop | def stop(self):
'''Stop listener.'''
self.logger.debug("Stopping listener.")
self.listener.stop()
if self.thread is not None:
self.thread.join()
self.thread = None
self.logger.debug("Listener stopped.") | python | def stop(self):
'''Stop listener.'''
self.logger.debug("Stopping listener.")
self.listener.stop()
if self.thread is not None:
self.thread.join()
self.thread = None
self.logger.debug("Listener stopped.") | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Stopping listener.\"",
")",
"self",
".",
"listener",
".",
"stop",
"(",
")",
"if",
"self",
".",
"thread",
"is",
"not",
"None",
":",
"self",
".",
"thread",
".",
"join",
... | Stop listener. | [
"Stop",
"listener",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/listener.py#L73-L80 | train | 49,707 |
pytroll/posttroll | posttroll/listener.py | Listener.create_subscriber | def create_subscriber(self):
'''Create a subscriber instance using specified addresses and
message types.
'''
if self.subscriber is None:
if self.topics:
self.subscriber = NSSubscriber(self.services, self.topics,
addr_listener=True,
addresses=self.addresses,
nameserver=self.nameserver)
self.recv = self.subscriber.start().recv | python | def create_subscriber(self):
'''Create a subscriber instance using specified addresses and
message types.
'''
if self.subscriber is None:
if self.topics:
self.subscriber = NSSubscriber(self.services, self.topics,
addr_listener=True,
addresses=self.addresses,
nameserver=self.nameserver)
self.recv = self.subscriber.start().recv | [
"def",
"create_subscriber",
"(",
"self",
")",
":",
"if",
"self",
".",
"subscriber",
"is",
"None",
":",
"if",
"self",
".",
"topics",
":",
"self",
".",
"subscriber",
"=",
"NSSubscriber",
"(",
"self",
".",
"services",
",",
"self",
".",
"topics",
",",
"add... | Create a subscriber instance using specified addresses and
message types. | [
"Create",
"a",
"subscriber",
"instance",
"using",
"specified",
"addresses",
"and",
"message",
"types",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/listener.py#L105-L115 | train | 49,708 |
pytroll/posttroll | posttroll/listener.py | Listener.stop | def stop(self):
'''Stop subscriber and delete the instance
'''
self.running = False
time.sleep(1)
if self.subscriber is not None:
self.subscriber.stop()
self.subscriber = None | python | def stop(self):
'''Stop subscriber and delete the instance
'''
self.running = False
time.sleep(1)
if self.subscriber is not None:
self.subscriber.stop()
self.subscriber = None | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"running",
"=",
"False",
"time",
".",
"sleep",
"(",
"1",
")",
"if",
"self",
".",
"subscriber",
"is",
"not",
"None",
":",
"self",
".",
"subscriber",
".",
"stop",
"(",
")",
"self",
".",
"subscriber",... | Stop subscriber and delete the instance | [
"Stop",
"subscriber",
"and",
"delete",
"the",
"instance"
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/listener.py#L138-L145 | train | 49,709 |
ARMmbed/autoversion | src/auto_version/semver.py | get_current_semver | def get_current_semver(data):
"""Given a dictionary of all version data available, determine the current version"""
# get the not-none values from data
known = {
key: data.get(alias)
for key, alias in config._forward_aliases.items()
if data.get(alias) is not None
}
# prefer the strict field, if available
potentials = [
known.pop(Constants.VERSION_STRICT_FIELD, None),
known.pop(Constants.VERSION_FIELD, None),
]
from_components = [known.get(k) for k in SemVerSigFig._fields if k in known]
if len(from_components) == 3:
potentials.append(".".join(from_components))
versions = set()
for potential in potentials:
if not potential:
continue
match = re_semver.match(potential)
if match:
parts = match.groupdict()
parts.pop("tail")
versions.add(SemVer(**parts))
if len(versions) > 1:
raise ValueError("conflicting versions within project: %s" % versions)
if not versions:
_LOG.debug("key pairs found: \n%r", known)
raise ValueError("could not find existing semver")
return versions.pop() | python | def get_current_semver(data):
"""Given a dictionary of all version data available, determine the current version"""
# get the not-none values from data
known = {
key: data.get(alias)
for key, alias in config._forward_aliases.items()
if data.get(alias) is not None
}
# prefer the strict field, if available
potentials = [
known.pop(Constants.VERSION_STRICT_FIELD, None),
known.pop(Constants.VERSION_FIELD, None),
]
from_components = [known.get(k) for k in SemVerSigFig._fields if k in known]
if len(from_components) == 3:
potentials.append(".".join(from_components))
versions = set()
for potential in potentials:
if not potential:
continue
match = re_semver.match(potential)
if match:
parts = match.groupdict()
parts.pop("tail")
versions.add(SemVer(**parts))
if len(versions) > 1:
raise ValueError("conflicting versions within project: %s" % versions)
if not versions:
_LOG.debug("key pairs found: \n%r", known)
raise ValueError("could not find existing semver")
return versions.pop() | [
"def",
"get_current_semver",
"(",
"data",
")",
":",
"# get the not-none values from data",
"known",
"=",
"{",
"key",
":",
"data",
".",
"get",
"(",
"alias",
")",
"for",
"key",
",",
"alias",
"in",
"config",
".",
"_forward_aliases",
".",
"items",
"(",
")",
"i... | Given a dictionary of all version data available, determine the current version | [
"Given",
"a",
"dictionary",
"of",
"all",
"version",
"data",
"available",
"determine",
"the",
"current",
"version"
] | c5b127d2059c8219f5637fe45bf9e1be3a0af2aa | https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/semver.py#L15-L50 | train | 49,710 |
ARMmbed/autoversion | src/auto_version/semver.py | make_new_semver | def make_new_semver(current_semver, all_triggers, **overrides):
"""Defines how to increment semver based on which significant figure is triggered"""
new_semver = {}
bumped = False
for sig_fig in SemVerSigFig: # iterate sig figs in order of significance
value = getattr(current_semver, sig_fig)
override = overrides.get(sig_fig)
if override is not None:
new_semver[sig_fig] = override
if int(override) > int(value):
bumped = True
elif bumped:
new_semver[sig_fig] = "0"
elif sig_fig in all_triggers:
new_semver[sig_fig] = str(int(value) + 1)
bumped = True
else:
new_semver[sig_fig] = value
return SemVer(**new_semver) | python | def make_new_semver(current_semver, all_triggers, **overrides):
"""Defines how to increment semver based on which significant figure is triggered"""
new_semver = {}
bumped = False
for sig_fig in SemVerSigFig: # iterate sig figs in order of significance
value = getattr(current_semver, sig_fig)
override = overrides.get(sig_fig)
if override is not None:
new_semver[sig_fig] = override
if int(override) > int(value):
bumped = True
elif bumped:
new_semver[sig_fig] = "0"
elif sig_fig in all_triggers:
new_semver[sig_fig] = str(int(value) + 1)
bumped = True
else:
new_semver[sig_fig] = value
return SemVer(**new_semver) | [
"def",
"make_new_semver",
"(",
"current_semver",
",",
"all_triggers",
",",
"*",
"*",
"overrides",
")",
":",
"new_semver",
"=",
"{",
"}",
"bumped",
"=",
"False",
"for",
"sig_fig",
"in",
"SemVerSigFig",
":",
"# iterate sig figs in order of significance",
"value",
"=... | Defines how to increment semver based on which significant figure is triggered | [
"Defines",
"how",
"to",
"increment",
"semver",
"based",
"on",
"which",
"significant",
"figure",
"is",
"triggered"
] | c5b127d2059c8219f5637fe45bf9e1be3a0af2aa | https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/semver.py#L53-L71 | train | 49,711 |
lbenitez000/trparse | trparse.py | loads | def loads(data):
"""Parser entry point. Parses the output of a traceroute execution"""
data += "\n_EOS_" # Append EOS token. Helps to match last RE_HOP
# Get headers
match_dest = RE_HEADER.search(data)
dest_name = match_dest.group(1)
dest_ip = match_dest.group(2)
# The Traceroute is the root of the tree.
traceroute = Traceroute(dest_name, dest_ip)
# Get hops
matches_hop = RE_HOP.findall(data)
for match_hop in matches_hop:
# Initialize a hop
idx = int(match_hop[0])
if match_hop[1]:
asn = int(match_hop[1])
else:
asn = None
hop = Hop(idx, asn)
# Parse probes data: <name> | <(IP)> | <rtt> | 'ms' | '*'
probes_data = match_hop[2].split()
# Get rid of 'ms': <name> | <(IP)> | <rtt> | '*'
probes_data = filter(lambda s: s.lower() != 'ms', probes_data)
i = 0
while i < len(probes_data):
# For each hop parse probes
name = None
ip = None
rtt = None
anno = ''
# RTT check comes first because RE_PROBE_NAME can confuse rtt with an IP as name
# The regex RE_PROBE_NAME can be improved
if RE_PROBE_RTT.match(probes_data[i]):
# Matched rtt, so name and IP have been parsed before
rtt = float(probes_data[i])
i += 1
elif RE_PROBE_NAME.match(probes_data[i]):
# Matched a name, so next elements are IP and rtt
name = probes_data[i]
ip = probes_data[i+1].strip('()')
rtt = float(probes_data[i+2])
i += 3
elif RE_PROBE_TIMEOUT.match(probes_data[i]):
# Its a timeout, so maybe name and IP have been parsed before
# or maybe not. But it's Hop job to deal with it
rtt = None
i += 1
else:
ext = "i: %d\nprobes_data: %s\nname: %s\nip: %s\nrtt: %s\nanno: %s" % (i, probes_data, name, ip, rtt, anno)
raise ParseError("Parse error \n%s" % ext)
# Check for annotation
try:
if RE_PROBE_ANNOTATION.match(probes_data[i]):
anno = probes_data[i]
i += 1
except IndexError:
pass
probe = Probe(name, ip, rtt, anno)
hop.add_probe(probe)
traceroute.add_hop(hop)
return traceroute | python | def loads(data):
"""Parser entry point. Parses the output of a traceroute execution"""
data += "\n_EOS_" # Append EOS token. Helps to match last RE_HOP
# Get headers
match_dest = RE_HEADER.search(data)
dest_name = match_dest.group(1)
dest_ip = match_dest.group(2)
# The Traceroute is the root of the tree.
traceroute = Traceroute(dest_name, dest_ip)
# Get hops
matches_hop = RE_HOP.findall(data)
for match_hop in matches_hop:
# Initialize a hop
idx = int(match_hop[0])
if match_hop[1]:
asn = int(match_hop[1])
else:
asn = None
hop = Hop(idx, asn)
# Parse probes data: <name> | <(IP)> | <rtt> | 'ms' | '*'
probes_data = match_hop[2].split()
# Get rid of 'ms': <name> | <(IP)> | <rtt> | '*'
probes_data = filter(lambda s: s.lower() != 'ms', probes_data)
i = 0
while i < len(probes_data):
# For each hop parse probes
name = None
ip = None
rtt = None
anno = ''
# RTT check comes first because RE_PROBE_NAME can confuse rtt with an IP as name
# The regex RE_PROBE_NAME can be improved
if RE_PROBE_RTT.match(probes_data[i]):
# Matched rtt, so name and IP have been parsed before
rtt = float(probes_data[i])
i += 1
elif RE_PROBE_NAME.match(probes_data[i]):
# Matched a name, so next elements are IP and rtt
name = probes_data[i]
ip = probes_data[i+1].strip('()')
rtt = float(probes_data[i+2])
i += 3
elif RE_PROBE_TIMEOUT.match(probes_data[i]):
# Its a timeout, so maybe name and IP have been parsed before
# or maybe not. But it's Hop job to deal with it
rtt = None
i += 1
else:
ext = "i: %d\nprobes_data: %s\nname: %s\nip: %s\nrtt: %s\nanno: %s" % (i, probes_data, name, ip, rtt, anno)
raise ParseError("Parse error \n%s" % ext)
# Check for annotation
try:
if RE_PROBE_ANNOTATION.match(probes_data[i]):
anno = probes_data[i]
i += 1
except IndexError:
pass
probe = Probe(name, ip, rtt, anno)
hop.add_probe(probe)
traceroute.add_hop(hop)
return traceroute | [
"def",
"loads",
"(",
"data",
")",
":",
"data",
"+=",
"\"\\n_EOS_\"",
"# Append EOS token. Helps to match last RE_HOP",
"# Get headers",
"match_dest",
"=",
"RE_HEADER",
".",
"search",
"(",
"data",
")",
"dest_name",
"=",
"match_dest",
".",
"group",
"(",
"1",
")",
... | Parser entry point. Parses the output of a traceroute execution | [
"Parser",
"entry",
"point",
".",
"Parses",
"the",
"output",
"of",
"a",
"traceroute",
"execution"
] | 1f932d882a98b062b540b6f4bc2ecb0f35b92e97 | https://github.com/lbenitez000/trparse/blob/1f932d882a98b062b540b6f4bc2ecb0f35b92e97/trparse.py#L88-L158 | train | 49,712 |
lbenitez000/trparse | trparse.py | Hop.add_probe | def add_probe(self, probe):
"""Adds a Probe instance to this hop's results."""
if self.probes:
probe_last = self.probes[-1]
if not probe.ip:
probe.ip = probe_last.ip
probe.name = probe_last.name
self.probes.append(probe) | python | def add_probe(self, probe):
"""Adds a Probe instance to this hop's results."""
if self.probes:
probe_last = self.probes[-1]
if not probe.ip:
probe.ip = probe_last.ip
probe.name = probe_last.name
self.probes.append(probe) | [
"def",
"add_probe",
"(",
"self",
",",
"probe",
")",
":",
"if",
"self",
".",
"probes",
":",
"probe_last",
"=",
"self",
".",
"probes",
"[",
"-",
"1",
"]",
"if",
"not",
"probe",
".",
"ip",
":",
"probe",
".",
"ip",
"=",
"probe_last",
".",
"ip",
"prob... | Adds a Probe instance to this hop's results. | [
"Adds",
"a",
"Probe",
"instance",
"to",
"this",
"hop",
"s",
"results",
"."
] | 1f932d882a98b062b540b6f4bc2ecb0f35b92e97 | https://github.com/lbenitez000/trparse/blob/1f932d882a98b062b540b6f4bc2ecb0f35b92e97/trparse.py#L48-L55 | train | 49,713 |
emichael/PyREM | pyrem/utils.py | synchronized | def synchronized(func, *args, **kwargs):
"""Function decorator to make function synchronized on ``self._lock``.
If the first argument to the function (hopefully self) does not have a _lock
attribute, then this decorator does nothing.
"""
if not (args and hasattr(args[0], '_lock')):
return func(*args, **kwargs)
with args[0]._lock: # pylint: disable=W0212
return func(*args, **kwargs) | python | def synchronized(func, *args, **kwargs):
"""Function decorator to make function synchronized on ``self._lock``.
If the first argument to the function (hopefully self) does not have a _lock
attribute, then this decorator does nothing.
"""
if not (args and hasattr(args[0], '_lock')):
return func(*args, **kwargs)
with args[0]._lock: # pylint: disable=W0212
return func(*args, **kwargs) | [
"def",
"synchronized",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"(",
"args",
"and",
"hasattr",
"(",
"args",
"[",
"0",
"]",
",",
"'_lock'",
")",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
... | Function decorator to make function synchronized on ``self._lock``.
If the first argument to the function (hopefully self) does not have a _lock
attribute, then this decorator does nothing. | [
"Function",
"decorator",
"to",
"make",
"function",
"synchronized",
"on",
"self",
".",
"_lock",
"."
] | 2609249ead197cd9496d164f4998ca9985503579 | https://github.com/emichael/PyREM/blob/2609249ead197cd9496d164f4998ca9985503579/pyrem/utils.py#L10-L19 | train | 49,714 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | normalize_job_id | def normalize_job_id(job_id):
"""
Convert a value to a job id.
:param job_id: Value to convert.
:type job_id: int, str
:return: The job id.
:rtype: :py:class:`uuid.UUID`
"""
if not isinstance(job_id, uuid.UUID):
job_id = uuid.UUID(job_id)
return job_id | python | def normalize_job_id(job_id):
"""
Convert a value to a job id.
:param job_id: Value to convert.
:type job_id: int, str
:return: The job id.
:rtype: :py:class:`uuid.UUID`
"""
if not isinstance(job_id, uuid.UUID):
job_id = uuid.UUID(job_id)
return job_id | [
"def",
"normalize_job_id",
"(",
"job_id",
")",
":",
"if",
"not",
"isinstance",
"(",
"job_id",
",",
"uuid",
".",
"UUID",
")",
":",
"job_id",
"=",
"uuid",
".",
"UUID",
"(",
"job_id",
")",
"return",
"job_id"
] | Convert a value to a job id.
:param job_id: Value to convert.
:type job_id: int, str
:return: The job id.
:rtype: :py:class:`uuid.UUID` | [
"Convert",
"a",
"value",
"to",
"a",
"job",
"id",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L41-L52 | train | 49,715 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | JobManager.start | def start(self):
"""
Start the JobManager thread.
"""
if self._thread_running.is_set():
raise RuntimeError('the JobManager has already been started')
self._thread.start()
self._thread_running.wait()
return | python | def start(self):
"""
Start the JobManager thread.
"""
if self._thread_running.is_set():
raise RuntimeError('the JobManager has already been started')
self._thread.start()
self._thread_running.wait()
return | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_thread_running",
".",
"is_set",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'the JobManager has already been started'",
")",
"self",
".",
"_thread",
".",
"start",
"(",
")",
"self",
".",
"_thread_r... | Start the JobManager thread. | [
"Start",
"the",
"JobManager",
"thread",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L209-L217 | train | 49,716 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | JobManager.stop | def stop(self):
"""
Stop the JobManager thread.
"""
self.logger.debug('stopping the job manager')
self._thread_running.clear()
self._thread_shutdown.wait()
self._job_lock.acquire()
self.logger.debug('waiting on ' + str(len(self._jobs)) + ' job threads')
for job_desc in self._jobs.values():
if job_desc['job'] is None:
continue
if not job_desc['job'].is_alive():
continue
job_desc['job'].join()
# the job lock must be released before the thread can be joined because the thread routine acquires it before
# checking if it should exit, see https://github.com/zeroSteiner/smoke-zephyr/issues/4 for more details
self._job_lock.release()
self._thread.join()
self.logger.info('the job manager has been stopped')
return | python | def stop(self):
"""
Stop the JobManager thread.
"""
self.logger.debug('stopping the job manager')
self._thread_running.clear()
self._thread_shutdown.wait()
self._job_lock.acquire()
self.logger.debug('waiting on ' + str(len(self._jobs)) + ' job threads')
for job_desc in self._jobs.values():
if job_desc['job'] is None:
continue
if not job_desc['job'].is_alive():
continue
job_desc['job'].join()
# the job lock must be released before the thread can be joined because the thread routine acquires it before
# checking if it should exit, see https://github.com/zeroSteiner/smoke-zephyr/issues/4 for more details
self._job_lock.release()
self._thread.join()
self.logger.info('the job manager has been stopped')
return | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'stopping the job manager'",
")",
"self",
".",
"_thread_running",
".",
"clear",
"(",
")",
"self",
".",
"_thread_shutdown",
".",
"wait",
"(",
")",
"self",
".",
"_job_lock",
"... | Stop the JobManager thread. | [
"Stop",
"the",
"JobManager",
"thread",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L219-L241 | train | 49,717 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | JobManager.job_run | def job_run(self, callback, parameters=None):
"""
Add a job and run it once immediately.
:param function callback: The function to run asynchronously.
:param parameters: The parameters to be provided to the callback.
:type parameters: list, tuple
:return: The job id.
:rtype: :py:class:`uuid.UUID`
"""
if not self._thread_running.is_set():
raise RuntimeError('the JobManager is not running')
parameters = (parameters or ())
if not isinstance(parameters, (list, tuple)):
parameters = (parameters,)
job_desc = {}
job_desc['job'] = JobRun(callback, parameters)
job_desc['last_run'] = None
job_desc['run_every'] = datetime.timedelta(0, 1)
job_desc['callback'] = callback
job_desc['parameters'] = parameters
job_desc['enabled'] = True
job_desc['tolerate_exceptions'] = False
job_desc['run_count'] = 0
job_desc['expiration'] = 0
job_id = uuid.uuid4()
self.logger.info('adding new job with id: ' + str(job_id) + ' and callback function: ' + callback.__name__)
with self._job_lock:
self._jobs[job_id] = job_desc
self._job_execute(job_id)
return job_id | python | def job_run(self, callback, parameters=None):
"""
Add a job and run it once immediately.
:param function callback: The function to run asynchronously.
:param parameters: The parameters to be provided to the callback.
:type parameters: list, tuple
:return: The job id.
:rtype: :py:class:`uuid.UUID`
"""
if not self._thread_running.is_set():
raise RuntimeError('the JobManager is not running')
parameters = (parameters or ())
if not isinstance(parameters, (list, tuple)):
parameters = (parameters,)
job_desc = {}
job_desc['job'] = JobRun(callback, parameters)
job_desc['last_run'] = None
job_desc['run_every'] = datetime.timedelta(0, 1)
job_desc['callback'] = callback
job_desc['parameters'] = parameters
job_desc['enabled'] = True
job_desc['tolerate_exceptions'] = False
job_desc['run_count'] = 0
job_desc['expiration'] = 0
job_id = uuid.uuid4()
self.logger.info('adding new job with id: ' + str(job_id) + ' and callback function: ' + callback.__name__)
with self._job_lock:
self._jobs[job_id] = job_desc
self._job_execute(job_id)
return job_id | [
"def",
"job_run",
"(",
"self",
",",
"callback",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_thread_running",
".",
"is_set",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'the JobManager is not running'",
")",
"parameters",
"=",
"(",... | Add a job and run it once immediately.
:param function callback: The function to run asynchronously.
:param parameters: The parameters to be provided to the callback.
:type parameters: list, tuple
:return: The job id.
:rtype: :py:class:`uuid.UUID` | [
"Add",
"a",
"job",
"and",
"run",
"it",
"once",
"immediately",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L243-L273 | train | 49,718 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | JobManager.job_add | def job_add(self, callback, parameters=None, hours=0, minutes=0, seconds=0, tolerate_exceptions=True, expiration=None):
"""
Add a job to the job manager.
:param function callback: The function to run asynchronously.
:param parameters: The parameters to be provided to the callback.
:type parameters: list, tuple
:param int hours: Number of hours to sleep between running the callback.
:param int minutes: Number of minutes to sleep between running the callback.
:param int seconds: Number of seconds to sleep between running the callback.
:param bool tolerate_execptions: Whether to continue running a job after it has thrown an exception.
:param expiration: When to expire and remove the job. If an integer
is provided, the job will be executed that many times. If a
datetime or timedelta instance is provided, then the job will
be removed after the specified time.
:type expiration: int, :py:class:`datetime.timedelta`, :py:class:`datetime.datetime`
:return: The job id.
:rtype: :py:class:`uuid.UUID`
"""
if not self._thread_running.is_set():
raise RuntimeError('the JobManager is not running')
parameters = (parameters or ())
if not isinstance(parameters, (list, tuple)):
parameters = (parameters,)
job_desc = {}
job_desc['job'] = JobRun(callback, parameters)
job_desc['last_run'] = None
job_desc['run_every'] = datetime.timedelta(0, ((hours * 60 * 60) + (minutes * 60) + seconds))
job_desc['callback'] = callback
job_desc['parameters'] = parameters
job_desc['enabled'] = True
job_desc['tolerate_exceptions'] = tolerate_exceptions
job_desc['run_count'] = 0
if isinstance(expiration, int):
job_desc['expiration'] = expiration
elif isinstance(expiration, datetime.timedelta):
job_desc['expiration'] = self.now() + expiration
elif isinstance(expiration, datetime.datetime):
job_desc['expiration'] = expiration
else:
job_desc['expiration'] = None
job_id = uuid.uuid4()
self.logger.info('adding new job with id: ' + str(job_id) + ' and callback function: ' + callback.__name__)
with self._job_lock:
self._jobs[job_id] = job_desc
return job_id | python | def job_add(self, callback, parameters=None, hours=0, minutes=0, seconds=0, tolerate_exceptions=True, expiration=None):
"""
Add a job to the job manager.
:param function callback: The function to run asynchronously.
:param parameters: The parameters to be provided to the callback.
:type parameters: list, tuple
:param int hours: Number of hours to sleep between running the callback.
:param int minutes: Number of minutes to sleep between running the callback.
:param int seconds: Number of seconds to sleep between running the callback.
:param bool tolerate_execptions: Whether to continue running a job after it has thrown an exception.
:param expiration: When to expire and remove the job. If an integer
is provided, the job will be executed that many times. If a
datetime or timedelta instance is provided, then the job will
be removed after the specified time.
:type expiration: int, :py:class:`datetime.timedelta`, :py:class:`datetime.datetime`
:return: The job id.
:rtype: :py:class:`uuid.UUID`
"""
if not self._thread_running.is_set():
raise RuntimeError('the JobManager is not running')
parameters = (parameters or ())
if not isinstance(parameters, (list, tuple)):
parameters = (parameters,)
job_desc = {}
job_desc['job'] = JobRun(callback, parameters)
job_desc['last_run'] = None
job_desc['run_every'] = datetime.timedelta(0, ((hours * 60 * 60) + (minutes * 60) + seconds))
job_desc['callback'] = callback
job_desc['parameters'] = parameters
job_desc['enabled'] = True
job_desc['tolerate_exceptions'] = tolerate_exceptions
job_desc['run_count'] = 0
if isinstance(expiration, int):
job_desc['expiration'] = expiration
elif isinstance(expiration, datetime.timedelta):
job_desc['expiration'] = self.now() + expiration
elif isinstance(expiration, datetime.datetime):
job_desc['expiration'] = expiration
else:
job_desc['expiration'] = None
job_id = uuid.uuid4()
self.logger.info('adding new job with id: ' + str(job_id) + ' and callback function: ' + callback.__name__)
with self._job_lock:
self._jobs[job_id] = job_desc
return job_id | [
"def",
"job_add",
"(",
"self",
",",
"callback",
",",
"parameters",
"=",
"None",
",",
"hours",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"seconds",
"=",
"0",
",",
"tolerate_exceptions",
"=",
"True",
",",
"expiration",
"=",
"None",
")",
":",
"if",
"not"... | Add a job to the job manager.
:param function callback: The function to run asynchronously.
:param parameters: The parameters to be provided to the callback.
:type parameters: list, tuple
:param int hours: Number of hours to sleep between running the callback.
:param int minutes: Number of minutes to sleep between running the callback.
:param int seconds: Number of seconds to sleep between running the callback.
:param bool tolerate_execptions: Whether to continue running a job after it has thrown an exception.
:param expiration: When to expire and remove the job. If an integer
is provided, the job will be executed that many times. If a
datetime or timedelta instance is provided, then the job will
be removed after the specified time.
:type expiration: int, :py:class:`datetime.timedelta`, :py:class:`datetime.datetime`
:return: The job id.
:rtype: :py:class:`uuid.UUID` | [
"Add",
"a",
"job",
"to",
"the",
"job",
"manager",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L275-L320 | train | 49,719 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | JobManager.job_count_enabled | def job_count_enabled(self):
"""
Return the number of enabled jobs.
:return: The number of jobs that are enabled.
:rtype: int
"""
enabled = 0
for job_desc in self._jobs.values():
if job_desc['enabled']:
enabled += 1
return enabled | python | def job_count_enabled(self):
"""
Return the number of enabled jobs.
:return: The number of jobs that are enabled.
:rtype: int
"""
enabled = 0
for job_desc in self._jobs.values():
if job_desc['enabled']:
enabled += 1
return enabled | [
"def",
"job_count_enabled",
"(",
"self",
")",
":",
"enabled",
"=",
"0",
"for",
"job_desc",
"in",
"self",
".",
"_jobs",
".",
"values",
"(",
")",
":",
"if",
"job_desc",
"[",
"'enabled'",
"]",
":",
"enabled",
"+=",
"1",
"return",
"enabled"
] | Return the number of enabled jobs.
:return: The number of jobs that are enabled.
:rtype: int | [
"Return",
"the",
"number",
"of",
"enabled",
"jobs",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L331-L342 | train | 49,720 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | JobManager.job_enable | def job_enable(self, job_id):
"""
Enable a job.
:param job_id: Job identifier to enable.
:type job_id: :py:class:`uuid.UUID`
"""
job_id = normalize_job_id(job_id)
with self._job_lock:
job_desc = self._jobs[job_id]
job_desc['enabled'] = True | python | def job_enable(self, job_id):
"""
Enable a job.
:param job_id: Job identifier to enable.
:type job_id: :py:class:`uuid.UUID`
"""
job_id = normalize_job_id(job_id)
with self._job_lock:
job_desc = self._jobs[job_id]
job_desc['enabled'] = True | [
"def",
"job_enable",
"(",
"self",
",",
"job_id",
")",
":",
"job_id",
"=",
"normalize_job_id",
"(",
"job_id",
")",
"with",
"self",
".",
"_job_lock",
":",
"job_desc",
"=",
"self",
".",
"_jobs",
"[",
"job_id",
"]",
"job_desc",
"[",
"'enabled'",
"]",
"=",
... | Enable a job.
:param job_id: Job identifier to enable.
:type job_id: :py:class:`uuid.UUID` | [
"Enable",
"a",
"job",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L344-L354 | train | 49,721 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | JobManager.job_disable | def job_disable(self, job_id):
"""
Disable a job. Disabled jobs will not be executed.
:param job_id: Job identifier to disable.
:type job_id: :py:class:`uuid.UUID`
"""
job_id = normalize_job_id(job_id)
with self._job_lock:
job_desc = self._jobs[job_id]
job_desc['enabled'] = False | python | def job_disable(self, job_id):
"""
Disable a job. Disabled jobs will not be executed.
:param job_id: Job identifier to disable.
:type job_id: :py:class:`uuid.UUID`
"""
job_id = normalize_job_id(job_id)
with self._job_lock:
job_desc = self._jobs[job_id]
job_desc['enabled'] = False | [
"def",
"job_disable",
"(",
"self",
",",
"job_id",
")",
":",
"job_id",
"=",
"normalize_job_id",
"(",
"job_id",
")",
"with",
"self",
".",
"_job_lock",
":",
"job_desc",
"=",
"self",
".",
"_jobs",
"[",
"job_id",
"]",
"job_desc",
"[",
"'enabled'",
"]",
"=",
... | Disable a job. Disabled jobs will not be executed.
:param job_id: Job identifier to disable.
:type job_id: :py:class:`uuid.UUID` | [
"Disable",
"a",
"job",
".",
"Disabled",
"jobs",
"will",
"not",
"be",
"executed",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L356-L366 | train | 49,722 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | JobManager.job_delete | def job_delete(self, job_id, wait=True):
"""
Delete a job.
:param job_id: Job identifier to delete.
:type job_id: :py:class:`uuid.UUID`
:param bool wait: If the job is currently running, wait for it to complete before deleting it.
"""
job_id = normalize_job_id(job_id)
self.logger.info('deleting job with id: ' + str(job_id) + ' and callback function: ' + self._jobs[job_id]['callback'].__name__)
job_desc = self._jobs[job_id]
with self._job_lock:
job_desc['enabled'] = False
if wait and self.job_is_running(job_id):
job_desc['job'].join()
del self._jobs[job_id] | python | def job_delete(self, job_id, wait=True):
"""
Delete a job.
:param job_id: Job identifier to delete.
:type job_id: :py:class:`uuid.UUID`
:param bool wait: If the job is currently running, wait for it to complete before deleting it.
"""
job_id = normalize_job_id(job_id)
self.logger.info('deleting job with id: ' + str(job_id) + ' and callback function: ' + self._jobs[job_id]['callback'].__name__)
job_desc = self._jobs[job_id]
with self._job_lock:
job_desc['enabled'] = False
if wait and self.job_is_running(job_id):
job_desc['job'].join()
del self._jobs[job_id] | [
"def",
"job_delete",
"(",
"self",
",",
"job_id",
",",
"wait",
"=",
"True",
")",
":",
"job_id",
"=",
"normalize_job_id",
"(",
"job_id",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'deleting job with id: '",
"+",
"str",
"(",
"job_id",
")",
"+",
"' and c... | Delete a job.
:param job_id: Job identifier to delete.
:type job_id: :py:class:`uuid.UUID`
:param bool wait: If the job is currently running, wait for it to complete before deleting it. | [
"Delete",
"a",
"job",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L368-L383 | train | 49,723 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | JobManager.job_is_enabled | def job_is_enabled(self, job_id):
"""
Check if a job is enabled.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
"""
job_id = normalize_job_id(job_id)
job_desc = self._jobs[job_id]
return job_desc['enabled'] | python | def job_is_enabled(self, job_id):
"""
Check if a job is enabled.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
"""
job_id = normalize_job_id(job_id)
job_desc = self._jobs[job_id]
return job_desc['enabled'] | [
"def",
"job_is_enabled",
"(",
"self",
",",
"job_id",
")",
":",
"job_id",
"=",
"normalize_job_id",
"(",
"job_id",
")",
"job_desc",
"=",
"self",
".",
"_jobs",
"[",
"job_id",
"]",
"return",
"job_desc",
"[",
"'enabled'",
"]"
] | Check if a job is enabled.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool | [
"Check",
"if",
"a",
"job",
"is",
"enabled",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L396-L406 | train | 49,724 |
zeroSteiner/smoke-zephyr | smoke_zephyr/job.py | JobManager.job_is_running | def job_is_running(self, job_id):
"""
Check if a job is currently running. False is returned if the job does
not exist.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
"""
job_id = normalize_job_id(job_id)
if job_id not in self._jobs:
return False
job_desc = self._jobs[job_id]
if job_desc['job']:
return job_desc['job'].is_alive()
return False | python | def job_is_running(self, job_id):
"""
Check if a job is currently running. False is returned if the job does
not exist.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
"""
job_id = normalize_job_id(job_id)
if job_id not in self._jobs:
return False
job_desc = self._jobs[job_id]
if job_desc['job']:
return job_desc['job'].is_alive()
return False | [
"def",
"job_is_running",
"(",
"self",
",",
"job_id",
")",
":",
"job_id",
"=",
"normalize_job_id",
"(",
"job_id",
")",
"if",
"job_id",
"not",
"in",
"self",
".",
"_jobs",
":",
"return",
"False",
"job_desc",
"=",
"self",
".",
"_jobs",
"[",
"job_id",
"]",
... | Check if a job is currently running. False is returned if the job does
not exist.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool | [
"Check",
"if",
"a",
"job",
"is",
"currently",
"running",
".",
"False",
"is",
"returned",
"if",
"the",
"job",
"does",
"not",
"exist",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L408-L423 | train | 49,725 |
zeroSteiner/smoke-zephyr | smoke_zephyr/argparse_types.py | bin_b64_type | def bin_b64_type(arg):
"""An argparse type representing binary data encoded in base64."""
try:
arg = base64.standard_b64decode(arg)
except (binascii.Error, TypeError):
raise argparse.ArgumentTypeError("{0} is invalid base64 data".format(repr(arg)))
return arg | python | def bin_b64_type(arg):
"""An argparse type representing binary data encoded in base64."""
try:
arg = base64.standard_b64decode(arg)
except (binascii.Error, TypeError):
raise argparse.ArgumentTypeError("{0} is invalid base64 data".format(repr(arg)))
return arg | [
"def",
"bin_b64_type",
"(",
"arg",
")",
":",
"try",
":",
"arg",
"=",
"base64",
".",
"standard_b64decode",
"(",
"arg",
")",
"except",
"(",
"binascii",
".",
"Error",
",",
"TypeError",
")",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"{0} is in... | An argparse type representing binary data encoded in base64. | [
"An",
"argparse",
"type",
"representing",
"binary",
"data",
"encoded",
"in",
"base64",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/argparse_types.py#L78-L84 | train | 49,726 |
zeroSteiner/smoke-zephyr | smoke_zephyr/argparse_types.py | bin_hex_type | def bin_hex_type(arg):
"""An argparse type representing binary data encoded in hex."""
if re.match(r'^[a-f0-9]{2}(:[a-f0-9]{2})+$', arg, re.I):
arg = arg.replace(':', '')
elif re.match(r'^(\\x[a-f0-9]{2})+$', arg, re.I):
arg = arg.replace('\\x', '')
try:
arg = binascii.a2b_hex(arg)
except (binascii.Error, TypeError):
raise argparse.ArgumentTypeError("{0} is invalid hex data".format(repr(arg)))
return arg | python | def bin_hex_type(arg):
"""An argparse type representing binary data encoded in hex."""
if re.match(r'^[a-f0-9]{2}(:[a-f0-9]{2})+$', arg, re.I):
arg = arg.replace(':', '')
elif re.match(r'^(\\x[a-f0-9]{2})+$', arg, re.I):
arg = arg.replace('\\x', '')
try:
arg = binascii.a2b_hex(arg)
except (binascii.Error, TypeError):
raise argparse.ArgumentTypeError("{0} is invalid hex data".format(repr(arg)))
return arg | [
"def",
"bin_hex_type",
"(",
"arg",
")",
":",
"if",
"re",
".",
"match",
"(",
"r'^[a-f0-9]{2}(:[a-f0-9]{2})+$'",
",",
"arg",
",",
"re",
".",
"I",
")",
":",
"arg",
"=",
"arg",
".",
"replace",
"(",
"':'",
",",
"''",
")",
"elif",
"re",
".",
"match",
"("... | An argparse type representing binary data encoded in hex. | [
"An",
"argparse",
"type",
"representing",
"binary",
"data",
"encoded",
"in",
"hex",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/argparse_types.py#L86-L96 | train | 49,727 |
zeroSteiner/smoke-zephyr | smoke_zephyr/argparse_types.py | dir_type | def dir_type(arg):
"""An argparse type representing a valid directory."""
if not os.path.isdir(arg):
raise argparse.ArgumentTypeError("{0} is not a valid directory".format(repr(arg)))
return arg | python | def dir_type(arg):
"""An argparse type representing a valid directory."""
if not os.path.isdir(arg):
raise argparse.ArgumentTypeError("{0} is not a valid directory".format(repr(arg)))
return arg | [
"def",
"dir_type",
"(",
"arg",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"arg",
")",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"{0} is not a valid directory\"",
".",
"format",
"(",
"repr",
"(",
"arg",
")",
")",
")",
... | An argparse type representing a valid directory. | [
"An",
"argparse",
"type",
"representing",
"a",
"valid",
"directory",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/argparse_types.py#L98-L102 | train | 49,728 |
zeroSteiner/smoke-zephyr | smoke_zephyr/argparse_types.py | email_type | def email_type(arg):
"""An argparse type representing an email address."""
if not is_valid_email_address(arg):
raise argparse.ArgumentTypeError("{0} is not a valid email address".format(repr(arg)))
return arg | python | def email_type(arg):
"""An argparse type representing an email address."""
if not is_valid_email_address(arg):
raise argparse.ArgumentTypeError("{0} is not a valid email address".format(repr(arg)))
return arg | [
"def",
"email_type",
"(",
"arg",
")",
":",
"if",
"not",
"is_valid_email_address",
"(",
"arg",
")",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"{0} is not a valid email address\"",
".",
"format",
"(",
"repr",
"(",
"arg",
")",
")",
")",
"return",... | An argparse type representing an email address. | [
"An",
"argparse",
"type",
"representing",
"an",
"email",
"address",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/argparse_types.py#L104-L108 | train | 49,729 |
zeroSteiner/smoke-zephyr | smoke_zephyr/argparse_types.py | log_level_type | def log_level_type(arg):
"""An argparse type representing a logging level."""
if not arg.upper() in ('NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'):
raise argparse.ArgumentTypeError("{0} is not a valid log level".format(repr(arg)))
return getattr(logging, arg.upper()) | python | def log_level_type(arg):
"""An argparse type representing a logging level."""
if not arg.upper() in ('NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'):
raise argparse.ArgumentTypeError("{0} is not a valid log level".format(repr(arg)))
return getattr(logging, arg.upper()) | [
"def",
"log_level_type",
"(",
"arg",
")",
":",
"if",
"not",
"arg",
".",
"upper",
"(",
")",
"in",
"(",
"'NOTSET'",
",",
"'DEBUG'",
",",
"'INFO'",
",",
"'WARNING'",
",",
"'ERROR'",
",",
"'CRITICAL'",
")",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",... | An argparse type representing a logging level. | [
"An",
"argparse",
"type",
"representing",
"a",
"logging",
"level",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/argparse_types.py#L110-L114 | train | 49,730 |
zeroSteiner/smoke-zephyr | smoke_zephyr/argparse_types.py | port_type | def port_type(arg):
"""An argparse type representing a tcp or udp port number."""
error_msg = "{0} is not a valid port".format(repr(arg))
try:
arg = ast.literal_eval(arg)
except ValueError:
raise argparse.ArgumentTypeError(error_msg)
if arg < 0 or arg > 65535:
raise argparse.ArgumentTypeError(error_msg)
return arg | python | def port_type(arg):
"""An argparse type representing a tcp or udp port number."""
error_msg = "{0} is not a valid port".format(repr(arg))
try:
arg = ast.literal_eval(arg)
except ValueError:
raise argparse.ArgumentTypeError(error_msg)
if arg < 0 or arg > 65535:
raise argparse.ArgumentTypeError(error_msg)
return arg | [
"def",
"port_type",
"(",
"arg",
")",
":",
"error_msg",
"=",
"\"{0} is not a valid port\"",
".",
"format",
"(",
"repr",
"(",
"arg",
")",
")",
"try",
":",
"arg",
"=",
"ast",
".",
"literal_eval",
"(",
"arg",
")",
"except",
"ValueError",
":",
"raise",
"argpa... | An argparse type representing a tcp or udp port number. | [
"An",
"argparse",
"type",
"representing",
"a",
"tcp",
"or",
"udp",
"port",
"number",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/argparse_types.py#L116-L125 | train | 49,731 |
zeroSteiner/smoke-zephyr | smoke_zephyr/argparse_types.py | timespan_type | def timespan_type(arg):
"""An argparse type representing a timespan such as 6h for 6 hours."""
try:
arg = parse_timespan(arg)
except ValueError:
raise argparse.ArgumentTypeError("{0} is not a valid time span".format(repr(arg)))
return arg | python | def timespan_type(arg):
"""An argparse type representing a timespan such as 6h for 6 hours."""
try:
arg = parse_timespan(arg)
except ValueError:
raise argparse.ArgumentTypeError("{0} is not a valid time span".format(repr(arg)))
return arg | [
"def",
"timespan_type",
"(",
"arg",
")",
":",
"try",
":",
"arg",
"=",
"parse_timespan",
"(",
"arg",
")",
"except",
"ValueError",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"{0} is not a valid time span\"",
".",
"format",
"(",
"repr",
"(",
"arg"... | An argparse type representing a timespan such as 6h for 6 hours. | [
"An",
"argparse",
"type",
"representing",
"a",
"timespan",
"such",
"as",
"6h",
"for",
"6",
"hours",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/argparse_types.py#L127-L133 | train | 49,732 |
pytroll/posttroll | posttroll/publisher.py | get_own_ip | def get_own_ip():
"""Get the host's ip number.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.connect(("8.8.8.8", 80))
except socket.gaierror:
ip_ = "127.0.0.1"
else:
ip_ = sock.getsockname()[0]
finally:
sock.close()
return ip_ | python | def get_own_ip():
"""Get the host's ip number.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.connect(("8.8.8.8", 80))
except socket.gaierror:
ip_ = "127.0.0.1"
else:
ip_ = sock.getsockname()[0]
finally:
sock.close()
return ip_ | [
"def",
"get_own_ip",
"(",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"try",
":",
"sock",
".",
"connect",
"(",
"(",
"\"8.8.8.8\"",
",",
"80",
")",
")",
"except",
"socket",
".",... | Get the host's ip number. | [
"Get",
"the",
"host",
"s",
"ip",
"number",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/publisher.py#L41-L53 | train | 49,733 |
pytroll/posttroll | posttroll/publisher.py | Publisher.send | def send(self, msg):
"""Send the given message.
"""
with self._pub_lock:
self.publish.send_string(msg)
return self | python | def send(self, msg):
"""Send the given message.
"""
with self._pub_lock:
self.publish.send_string(msg)
return self | [
"def",
"send",
"(",
"self",
",",
"msg",
")",
":",
"with",
"self",
".",
"_pub_lock",
":",
"self",
".",
"publish",
".",
"send_string",
"(",
"msg",
")",
"return",
"self"
] | Send the given message. | [
"Send",
"the",
"given",
"message",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/publisher.py#L119-L124 | train | 49,734 |
pytroll/posttroll | posttroll/publisher.py | NoisyPublisher.start | def start(self):
"""Start the publisher.
"""
pub_addr = "tcp://*:" + str(self._port)
self._publisher = self._publisher_class(pub_addr, self._name)
LOGGER.debug("entering publish %s", str(self._publisher.destination))
addr = ("tcp://" + str(get_own_ip()) + ":" +
str(self._publisher.port_number))
self._broadcaster = sendaddressservice(self._name, addr,
self._aliases,
self._broadcast_interval,
self._nameservers).start()
return self._publisher | python | def start(self):
"""Start the publisher.
"""
pub_addr = "tcp://*:" + str(self._port)
self._publisher = self._publisher_class(pub_addr, self._name)
LOGGER.debug("entering publish %s", str(self._publisher.destination))
addr = ("tcp://" + str(get_own_ip()) + ":" +
str(self._publisher.port_number))
self._broadcaster = sendaddressservice(self._name, addr,
self._aliases,
self._broadcast_interval,
self._nameservers).start()
return self._publisher | [
"def",
"start",
"(",
"self",
")",
":",
"pub_addr",
"=",
"\"tcp://*:\"",
"+",
"str",
"(",
"self",
".",
"_port",
")",
"self",
".",
"_publisher",
"=",
"self",
".",
"_publisher_class",
"(",
"pub_addr",
",",
"self",
".",
"_name",
")",
"LOGGER",
".",
"debug"... | Start the publisher. | [
"Start",
"the",
"publisher",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/publisher.py#L197-L209 | train | 49,735 |
zeroSteiner/smoke-zephyr | smoke_zephyr/utilities.py | configure_stream_logger | def configure_stream_logger(logger='', level=None, formatter='%(levelname)-8s %(message)s'):
"""
Configure the default stream handler for logging messages to the console,
remove other logging handlers, and enable capturing warnings.
.. versionadded:: 1.3.0
:param str logger: The logger to add the stream handler for.
:param level: The level to set the logger to, will default to WARNING if no level is specified.
:type level: None, int, str
:param formatter: The format to use for logging messages to the console.
:type formatter: str, :py:class:`logging.Formatter`
:return: The new configured stream handler.
:rtype: :py:class:`logging.StreamHandler`
"""
level = level or logging.WARNING
if isinstance(level, str):
level = getattr(logging, level, None)
if level is None:
raise ValueError('invalid log level: ' + level)
root_logger = logging.getLogger('')
for handler in root_logger.handlers:
root_logger.removeHandler(handler)
logging.getLogger(logger).setLevel(logging.DEBUG)
console_log_handler = logging.StreamHandler()
console_log_handler.setLevel(level)
if isinstance(formatter, str):
formatter = logging.Formatter(formatter)
elif not isinstance(formatter, logging.Formatter):
raise TypeError('formatter must be an instance of logging.Formatter')
console_log_handler.setFormatter(formatter)
logging.getLogger(logger).addHandler(console_log_handler)
logging.captureWarnings(True)
return console_log_handler | python | def configure_stream_logger(logger='', level=None, formatter='%(levelname)-8s %(message)s'):
"""
Configure the default stream handler for logging messages to the console,
remove other logging handlers, and enable capturing warnings.
.. versionadded:: 1.3.0
:param str logger: The logger to add the stream handler for.
:param level: The level to set the logger to, will default to WARNING if no level is specified.
:type level: None, int, str
:param formatter: The format to use for logging messages to the console.
:type formatter: str, :py:class:`logging.Formatter`
:return: The new configured stream handler.
:rtype: :py:class:`logging.StreamHandler`
"""
level = level or logging.WARNING
if isinstance(level, str):
level = getattr(logging, level, None)
if level is None:
raise ValueError('invalid log level: ' + level)
root_logger = logging.getLogger('')
for handler in root_logger.handlers:
root_logger.removeHandler(handler)
logging.getLogger(logger).setLevel(logging.DEBUG)
console_log_handler = logging.StreamHandler()
console_log_handler.setLevel(level)
if isinstance(formatter, str):
formatter = logging.Formatter(formatter)
elif not isinstance(formatter, logging.Formatter):
raise TypeError('formatter must be an instance of logging.Formatter')
console_log_handler.setFormatter(formatter)
logging.getLogger(logger).addHandler(console_log_handler)
logging.captureWarnings(True)
return console_log_handler | [
"def",
"configure_stream_logger",
"(",
"logger",
"=",
"''",
",",
"level",
"=",
"None",
",",
"formatter",
"=",
"'%(levelname)-8s %(message)s'",
")",
":",
"level",
"=",
"level",
"or",
"logging",
".",
"WARNING",
"if",
"isinstance",
"(",
"level",
",",
"str",
")"... | Configure the default stream handler for logging messages to the console,
remove other logging handlers, and enable capturing warnings.
.. versionadded:: 1.3.0
:param str logger: The logger to add the stream handler for.
:param level: The level to set the logger to, will default to WARNING if no level is specified.
:type level: None, int, str
:param formatter: The format to use for logging messages to the console.
:type formatter: str, :py:class:`logging.Formatter`
:return: The new configured stream handler.
:rtype: :py:class:`logging.StreamHandler` | [
"Configure",
"the",
"default",
"stream",
"handler",
"for",
"logging",
"messages",
"to",
"the",
"console",
"remove",
"other",
"logging",
"handlers",
"and",
"enable",
"capturing",
"warnings",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L420-L454 | train | 49,736 |
zeroSteiner/smoke-zephyr | smoke_zephyr/utilities.py | format_bytes_size | def format_bytes_size(val):
"""
Take a number of bytes and convert it to a human readable number.
:param int val: The number of bytes to format.
:return: The size in a human readable format.
:rtype: str
"""
if not val:
return '0 bytes'
for sz_name in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']:
if val < 1024.0:
return "{0:.2f} {1}".format(val, sz_name)
val /= 1024.0
raise OverflowError() | python | def format_bytes_size(val):
"""
Take a number of bytes and convert it to a human readable number.
:param int val: The number of bytes to format.
:return: The size in a human readable format.
:rtype: str
"""
if not val:
return '0 bytes'
for sz_name in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']:
if val < 1024.0:
return "{0:.2f} {1}".format(val, sz_name)
val /= 1024.0
raise OverflowError() | [
"def",
"format_bytes_size",
"(",
"val",
")",
":",
"if",
"not",
"val",
":",
"return",
"'0 bytes'",
"for",
"sz_name",
"in",
"[",
"'bytes'",
",",
"'KB'",
",",
"'MB'",
",",
"'GB'",
",",
"'TB'",
",",
"'PB'",
",",
"'EB'",
"]",
":",
"if",
"val",
"<",
"102... | Take a number of bytes and convert it to a human readable number.
:param int val: The number of bytes to format.
:return: The size in a human readable format.
:rtype: str | [
"Take",
"a",
"number",
"of",
"bytes",
"and",
"convert",
"it",
"to",
"a",
"human",
"readable",
"number",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L485-L499 | train | 49,737 |
zeroSteiner/smoke-zephyr | smoke_zephyr/utilities.py | grep | def grep(expression, file, flags=0, invert=False):
"""
Search a file and return a list of all lines that match a regular expression.
:param str expression: The regex to search for.
:param file: The file to search in.
:type file: str, file
:param int flags: The regex flags to use when searching.
:param bool invert: Select non matching lines instead.
:return: All the matching lines.
:rtype: list
"""
# requirements = re
if isinstance(file, str):
file = open(file)
lines = []
for line in file:
if bool(re.search(expression, line, flags=flags)) ^ invert:
lines.append(line)
return lines | python | def grep(expression, file, flags=0, invert=False):
"""
Search a file and return a list of all lines that match a regular expression.
:param str expression: The regex to search for.
:param file: The file to search in.
:type file: str, file
:param int flags: The regex flags to use when searching.
:param bool invert: Select non matching lines instead.
:return: All the matching lines.
:rtype: list
"""
# requirements = re
if isinstance(file, str):
file = open(file)
lines = []
for line in file:
if bool(re.search(expression, line, flags=flags)) ^ invert:
lines.append(line)
return lines | [
"def",
"grep",
"(",
"expression",
",",
"file",
",",
"flags",
"=",
"0",
",",
"invert",
"=",
"False",
")",
":",
"# requirements = re",
"if",
"isinstance",
"(",
"file",
",",
"str",
")",
":",
"file",
"=",
"open",
"(",
"file",
")",
"lines",
"=",
"[",
"]... | Search a file and return a list of all lines that match a regular expression.
:param str expression: The regex to search for.
:param file: The file to search in.
:type file: str, file
:param int flags: The regex flags to use when searching.
:param bool invert: Select non matching lines instead.
:return: All the matching lines.
:rtype: list | [
"Search",
"a",
"file",
"and",
"return",
"a",
"list",
"of",
"all",
"lines",
"that",
"match",
"a",
"regular",
"expression",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L501-L520 | train | 49,738 |
zeroSteiner/smoke-zephyr | smoke_zephyr/utilities.py | parse_case_snake_to_camel | def parse_case_snake_to_camel(snake, upper_first=True):
"""
Convert a string from snake_case to CamelCase.
:param str snake: The snake_case string to convert.
:param bool upper_first: Whether or not to capitalize the first
character of the string.
:return: The CamelCase version of string.
:rtype: str
"""
snake = snake.split('_')
first_part = snake[0]
if upper_first:
first_part = first_part.title()
return first_part + ''.join(word.title() for word in snake[1:]) | python | def parse_case_snake_to_camel(snake, upper_first=True):
"""
Convert a string from snake_case to CamelCase.
:param str snake: The snake_case string to convert.
:param bool upper_first: Whether or not to capitalize the first
character of the string.
:return: The CamelCase version of string.
:rtype: str
"""
snake = snake.split('_')
first_part = snake[0]
if upper_first:
first_part = first_part.title()
return first_part + ''.join(word.title() for word in snake[1:]) | [
"def",
"parse_case_snake_to_camel",
"(",
"snake",
",",
"upper_first",
"=",
"True",
")",
":",
"snake",
"=",
"snake",
".",
"split",
"(",
"'_'",
")",
"first_part",
"=",
"snake",
"[",
"0",
"]",
"if",
"upper_first",
":",
"first_part",
"=",
"first_part",
".",
... | Convert a string from snake_case to CamelCase.
:param str snake: The snake_case string to convert.
:param bool upper_first: Whether or not to capitalize the first
character of the string.
:return: The CamelCase version of string.
:rtype: str | [
"Convert",
"a",
"string",
"from",
"snake_case",
"to",
"CamelCase",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L577-L591 | train | 49,739 |
zeroSteiner/smoke-zephyr | smoke_zephyr/utilities.py | parse_to_slug | def parse_to_slug(words, maxlen=24):
"""
Parse a string into a slug format suitable for use in URLs and other
character restricted applications. Only utf-8 strings are supported at this
time.
:param str words: The words to parse.
:param int maxlen: The maximum length of the slug.
:return: The parsed words as a slug.
:rtype: str
"""
slug = ''
maxlen = min(maxlen, len(words))
for c in words:
if len(slug) == maxlen:
break
c = ord(c)
if c == 0x27:
continue
elif c >= 0x30 and c <= 0x39:
slug += chr(c)
elif c >= 0x41 and c <= 0x5a:
slug += chr(c + 0x20)
elif c >= 0x61 and c <= 0x7a:
slug += chr(c)
elif len(slug) and slug[-1] != '-':
slug += '-'
if len(slug) and slug[-1] == '-':
slug = slug[:-1]
return slug | python | def parse_to_slug(words, maxlen=24):
"""
Parse a string into a slug format suitable for use in URLs and other
character restricted applications. Only utf-8 strings are supported at this
time.
:param str words: The words to parse.
:param int maxlen: The maximum length of the slug.
:return: The parsed words as a slug.
:rtype: str
"""
slug = ''
maxlen = min(maxlen, len(words))
for c in words:
if len(slug) == maxlen:
break
c = ord(c)
if c == 0x27:
continue
elif c >= 0x30 and c <= 0x39:
slug += chr(c)
elif c >= 0x41 and c <= 0x5a:
slug += chr(c + 0x20)
elif c >= 0x61 and c <= 0x7a:
slug += chr(c)
elif len(slug) and slug[-1] != '-':
slug += '-'
if len(slug) and slug[-1] == '-':
slug = slug[:-1]
return slug | [
"def",
"parse_to_slug",
"(",
"words",
",",
"maxlen",
"=",
"24",
")",
":",
"slug",
"=",
"''",
"maxlen",
"=",
"min",
"(",
"maxlen",
",",
"len",
"(",
"words",
")",
")",
"for",
"c",
"in",
"words",
":",
"if",
"len",
"(",
"slug",
")",
"==",
"maxlen",
... | Parse a string into a slug format suitable for use in URLs and other
character restricted applications. Only utf-8 strings are supported at this
time.
:param str words: The words to parse.
:param int maxlen: The maximum length of the slug.
:return: The parsed words as a slug.
:rtype: str | [
"Parse",
"a",
"string",
"into",
"a",
"slug",
"format",
"suitable",
"for",
"use",
"in",
"URLs",
"and",
"other",
"character",
"restricted",
"applications",
".",
"Only",
"utf",
"-",
"8",
"strings",
"are",
"supported",
"at",
"this",
"time",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L662-L691 | train | 49,740 |
zeroSteiner/smoke-zephyr | smoke_zephyr/utilities.py | selection_collision | def selection_collision(selections, poolsize):
"""
Calculate the probability that two random values selected from an arbitrary
sized pool of unique values will be equal. This is commonly known as the
"Birthday Problem".
:param int selections: The number of random selections.
:param int poolsize: The number of unique random values in the pool to choose from.
:rtype: float
:return: The chance that a collision will occur as a percentage.
"""
# requirments = sys
probability = 100.0
poolsize = float(poolsize)
for i in range(selections):
probability = probability * (poolsize - i) / poolsize
probability = (100.0 - probability)
return probability | python | def selection_collision(selections, poolsize):
"""
Calculate the probability that two random values selected from an arbitrary
sized pool of unique values will be equal. This is commonly known as the
"Birthday Problem".
:param int selections: The number of random selections.
:param int poolsize: The number of unique random values in the pool to choose from.
:rtype: float
:return: The chance that a collision will occur as a percentage.
"""
# requirments = sys
probability = 100.0
poolsize = float(poolsize)
for i in range(selections):
probability = probability * (poolsize - i) / poolsize
probability = (100.0 - probability)
return probability | [
"def",
"selection_collision",
"(",
"selections",
",",
"poolsize",
")",
":",
"# requirments = sys",
"probability",
"=",
"100.0",
"poolsize",
"=",
"float",
"(",
"poolsize",
")",
"for",
"i",
"in",
"range",
"(",
"selections",
")",
":",
"probability",
"=",
"probabi... | Calculate the probability that two random values selected from an arbitrary
sized pool of unique values will be equal. This is commonly known as the
"Birthday Problem".
:param int selections: The number of random selections.
:param int poolsize: The number of unique random values in the pool to choose from.
:rtype: float
:return: The chance that a collision will occur as a percentage. | [
"Calculate",
"the",
"probability",
"that",
"two",
"random",
"values",
"selected",
"from",
"an",
"arbitrary",
"sized",
"pool",
"of",
"unique",
"values",
"will",
"be",
"equal",
".",
"This",
"is",
"commonly",
"known",
"as",
"the",
"Birthday",
"Problem",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L717-L734 | train | 49,741 |
zeroSteiner/smoke-zephyr | smoke_zephyr/utilities.py | unique | def unique(seq, key=None):
"""
Create a unique list or tuple from a provided list or tuple and preserve the
order.
:param seq: The list or tuple to preserve unique items from.
:type seq: list, tuple
:param key: If key is provided it will be called during the
comparison process.
:type key: function, None
"""
if key is None:
key = lambda x: x
preserved_type = type(seq)
if preserved_type not in (list, tuple):
raise TypeError("unique argument 1 must be list or tuple, not {0}".format(preserved_type.__name__))
seen = []
result = []
for item in seq:
marker = key(item)
if marker in seen:
continue
seen.append(marker)
result.append(item)
return preserved_type(result) | python | def unique(seq, key=None):
"""
Create a unique list or tuple from a provided list or tuple and preserve the
order.
:param seq: The list or tuple to preserve unique items from.
:type seq: list, tuple
:param key: If key is provided it will be called during the
comparison process.
:type key: function, None
"""
if key is None:
key = lambda x: x
preserved_type = type(seq)
if preserved_type not in (list, tuple):
raise TypeError("unique argument 1 must be list or tuple, not {0}".format(preserved_type.__name__))
seen = []
result = []
for item in seq:
marker = key(item)
if marker in seen:
continue
seen.append(marker)
result.append(item)
return preserved_type(result) | [
"def",
"unique",
"(",
"seq",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"lambda",
"x",
":",
"x",
"preserved_type",
"=",
"type",
"(",
"seq",
")",
"if",
"preserved_type",
"not",
"in",
"(",
"list",
",",
"tuple",
"... | Create a unique list or tuple from a provided list or tuple and preserve the
order.
:param seq: The list or tuple to preserve unique items from.
:type seq: list, tuple
:param key: If key is provided it will be called during the
comparison process.
:type key: function, None | [
"Create",
"a",
"unique",
"list",
"or",
"tuple",
"from",
"a",
"provided",
"list",
"or",
"tuple",
"and",
"preserve",
"the",
"order",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L748-L772 | train | 49,742 |
zeroSteiner/smoke-zephyr | smoke_zephyr/utilities.py | xfrange | def xfrange(start, stop=None, step=1):
"""
Iterate through an arithmetic progression.
:param start: Starting number.
:type start: float, int, long
:param stop: Stopping number.
:type stop: float, int, long
:param step: Stepping size.
:type step: float, int, long
"""
if stop is None:
stop = start
start = 0.0
start = float(start)
while start < stop:
yield start
start += step | python | def xfrange(start, stop=None, step=1):
"""
Iterate through an arithmetic progression.
:param start: Starting number.
:type start: float, int, long
:param stop: Stopping number.
:type stop: float, int, long
:param step: Stepping size.
:type step: float, int, long
"""
if stop is None:
stop = start
start = 0.0
start = float(start)
while start < stop:
yield start
start += step | [
"def",
"xfrange",
"(",
"start",
",",
"stop",
"=",
"None",
",",
"step",
"=",
"1",
")",
":",
"if",
"stop",
"is",
"None",
":",
"stop",
"=",
"start",
"start",
"=",
"0.0",
"start",
"=",
"float",
"(",
"start",
")",
"while",
"start",
"<",
"stop",
":",
... | Iterate through an arithmetic progression.
:param start: Starting number.
:type start: float, int, long
:param stop: Stopping number.
:type stop: float, int, long
:param step: Stepping size.
:type step: float, int, long | [
"Iterate",
"through",
"an",
"arithmetic",
"progression",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L824-L841 | train | 49,743 |
zeroSteiner/smoke-zephyr | smoke_zephyr/utilities.py | SectionConfigParser.set | def set(self, option, value):
"""
Set an option to an arbitrary value.
:param str option: The name of the option to set.
:param value: The value to set the option to.
"""
self.config_parser.set(self.section_name, option, value) | python | def set(self, option, value):
"""
Set an option to an arbitrary value.
:param str option: The name of the option to set.
:param value: The value to set the option to.
"""
self.config_parser.set(self.section_name, option, value) | [
"def",
"set",
"(",
"self",
",",
"option",
",",
"value",
")",
":",
"self",
".",
"config_parser",
".",
"set",
"(",
"self",
".",
"section_name",
",",
"option",
",",
"value",
")"
] | Set an option to an arbitrary value.
:param str option: The name of the option to set.
:param value: The value to set the option to. | [
"Set",
"an",
"option",
"to",
"an",
"arbitrary",
"value",
"."
] | a6d2498aeacc72ee52e7806f783a4d83d537ffb2 | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L396-L403 | train | 49,744 |
dusktreader/py-buzz | buzz/__init__.py | Buzz.reformat_exception | def reformat_exception(cls, message, err, *format_args, **format_kwds):
"""
Reformats an exception by adding a message to it and reporting the
original exception name and message
"""
final_message = message.format(*format_args, **format_kwds)
final_message = "{} -- {}: {}".format(
final_message,
type(err).__name__,
str(err),
)
final_message = cls.sanitize_errstr(final_message)
return final_message | python | def reformat_exception(cls, message, err, *format_args, **format_kwds):
"""
Reformats an exception by adding a message to it and reporting the
original exception name and message
"""
final_message = message.format(*format_args, **format_kwds)
final_message = "{} -- {}: {}".format(
final_message,
type(err).__name__,
str(err),
)
final_message = cls.sanitize_errstr(final_message)
return final_message | [
"def",
"reformat_exception",
"(",
"cls",
",",
"message",
",",
"err",
",",
"*",
"format_args",
",",
"*",
"*",
"format_kwds",
")",
":",
"final_message",
"=",
"message",
".",
"format",
"(",
"*",
"format_args",
",",
"*",
"*",
"format_kwds",
")",
"final_message... | Reformats an exception by adding a message to it and reporting the
original exception name and message | [
"Reformats",
"an",
"exception",
"by",
"adding",
"a",
"message",
"to",
"it",
"and",
"reporting",
"the",
"original",
"exception",
"name",
"and",
"message"
] | f2fd97abe158a1688188647992a5be6531058ec3 | https://github.com/dusktreader/py-buzz/blob/f2fd97abe158a1688188647992a5be6531058ec3/buzz/__init__.py#L52-L64 | train | 49,745 |
dusktreader/py-buzz | buzz/__init__.py | Buzz.require_condition | def require_condition(cls, expr, message, *format_args, **format_kwds):
"""
used to assert a certain state. If the expression renders a false
value, an exception will be raised with the supplied message
:param: message: The failure message to attach to the raised Buzz
:param: expr: A boolean value indicating an evaluated expression
:param: format_args: Format arguments. Follows str.format convention
:param: format_kwds: Format keyword args. Follows str.format convetion
"""
if not expr:
raise cls(message, *format_args, **format_kwds) | python | def require_condition(cls, expr, message, *format_args, **format_kwds):
"""
used to assert a certain state. If the expression renders a false
value, an exception will be raised with the supplied message
:param: message: The failure message to attach to the raised Buzz
:param: expr: A boolean value indicating an evaluated expression
:param: format_args: Format arguments. Follows str.format convention
:param: format_kwds: Format keyword args. Follows str.format convetion
"""
if not expr:
raise cls(message, *format_args, **format_kwds) | [
"def",
"require_condition",
"(",
"cls",
",",
"expr",
",",
"message",
",",
"*",
"format_args",
",",
"*",
"*",
"format_kwds",
")",
":",
"if",
"not",
"expr",
":",
"raise",
"cls",
"(",
"message",
",",
"*",
"format_args",
",",
"*",
"*",
"format_kwds",
")"
] | used to assert a certain state. If the expression renders a false
value, an exception will be raised with the supplied message
:param: message: The failure message to attach to the raised Buzz
:param: expr: A boolean value indicating an evaluated expression
:param: format_args: Format arguments. Follows str.format convention
:param: format_kwds: Format keyword args. Follows str.format convetion | [
"used",
"to",
"assert",
"a",
"certain",
"state",
".",
"If",
"the",
"expression",
"renders",
"a",
"false",
"value",
"an",
"exception",
"will",
"be",
"raised",
"with",
"the",
"supplied",
"message"
] | f2fd97abe158a1688188647992a5be6531058ec3 | https://github.com/dusktreader/py-buzz/blob/f2fd97abe158a1688188647992a5be6531058ec3/buzz/__init__.py#L136-L147 | train | 49,746 |
Nic30/sphinx-hwt | sphinx_hwt/sphinx_hwt.py | SchematicLink.visit_html | def visit_html(self, node):
"""
Generate html elements and schematic json
"""
parentClsNode = node.parent.parent
assert parentClsNode.attributes['objtype'] == 'class'
assert parentClsNode.attributes['domain'] == 'py'
sign = node.parent.parent.children[0]
assert isinstance(sign, desc_signature)
absolute_name = sign.attributes['ids'][0]
_construct = node["constructor_fn "]
serialno = node["serialno"]
try:
if _construct is None:
unitCls = generic_import(absolute_name)
if not issubclass(unitCls, Unit):
raise AssertionError(
"Can not use hwt-schematic sphinx directive and create schematic"
" for %s because it is not subclass of %r" % (absolute_name, Unit))
u = unitCls()
else:
assert len(_construct) > 0 and RE_IS_ID.match(_construct), _construct
_absolute_name = []
assert ".." not in absolute_name, absolute_name
for n in absolute_name.split(sep=".")[:-1]:
if n != "":
_absolute_name.append(n)
_absolute_name.append(_construct)
constructor_fn = generic_import(_absolute_name)
u = constructor_fn()
if not isinstance(u, Unit):
raise AssertionError(
"Can not use hwt-schematic sphinx directive and create schematic"
" for %s because function did not returned instance of %r, (%r)" % (
_absolute_name, Unit, u))
schem_file = SchematicPaths.get_sch_file_name_absolute(
self.document, absolute_name, serialno)
makedirs(path.dirname(schem_file), exist_ok=True)
with open(schem_file, "w") as f:
synthesised(u, DEFAULT_PLATFORM)
g = UnitToLNode(u, optimizations=DEFAULT_LAYOUT_OPTIMIZATIONS)
idStore = ElkIdStore()
data = g.toElkJson(idStore)
json.dump(data, f)
viewer = SchematicPaths.get_sch_viewer_link(self.document)
sch_name = SchematicPaths.get_sch_file_name(
self.document, absolute_name, serialno)
ref = nodes.reference(text=_("schematic"), # internal=False,
refuri="%s?schematic=%s" % (
viewer,
path.join(SchematicPaths.SCHEMATIC_DIR_PREFIX,
sch_name)))
node += ref
except Exception as e:
logging.error(e, exc_info=True)
raise Exception(
"Error occured while processing of %s" % absolute_name) | python | def visit_html(self, node):
"""
Generate html elements and schematic json
"""
parentClsNode = node.parent.parent
assert parentClsNode.attributes['objtype'] == 'class'
assert parentClsNode.attributes['domain'] == 'py'
sign = node.parent.parent.children[0]
assert isinstance(sign, desc_signature)
absolute_name = sign.attributes['ids'][0]
_construct = node["constructor_fn "]
serialno = node["serialno"]
try:
if _construct is None:
unitCls = generic_import(absolute_name)
if not issubclass(unitCls, Unit):
raise AssertionError(
"Can not use hwt-schematic sphinx directive and create schematic"
" for %s because it is not subclass of %r" % (absolute_name, Unit))
u = unitCls()
else:
assert len(_construct) > 0 and RE_IS_ID.match(_construct), _construct
_absolute_name = []
assert ".." not in absolute_name, absolute_name
for n in absolute_name.split(sep=".")[:-1]:
if n != "":
_absolute_name.append(n)
_absolute_name.append(_construct)
constructor_fn = generic_import(_absolute_name)
u = constructor_fn()
if not isinstance(u, Unit):
raise AssertionError(
"Can not use hwt-schematic sphinx directive and create schematic"
" for %s because function did not returned instance of %r, (%r)" % (
_absolute_name, Unit, u))
schem_file = SchematicPaths.get_sch_file_name_absolute(
self.document, absolute_name, serialno)
makedirs(path.dirname(schem_file), exist_ok=True)
with open(schem_file, "w") as f:
synthesised(u, DEFAULT_PLATFORM)
g = UnitToLNode(u, optimizations=DEFAULT_LAYOUT_OPTIMIZATIONS)
idStore = ElkIdStore()
data = g.toElkJson(idStore)
json.dump(data, f)
viewer = SchematicPaths.get_sch_viewer_link(self.document)
sch_name = SchematicPaths.get_sch_file_name(
self.document, absolute_name, serialno)
ref = nodes.reference(text=_("schematic"), # internal=False,
refuri="%s?schematic=%s" % (
viewer,
path.join(SchematicPaths.SCHEMATIC_DIR_PREFIX,
sch_name)))
node += ref
except Exception as e:
logging.error(e, exc_info=True)
raise Exception(
"Error occured while processing of %s" % absolute_name) | [
"def",
"visit_html",
"(",
"self",
",",
"node",
")",
":",
"parentClsNode",
"=",
"node",
".",
"parent",
".",
"parent",
"assert",
"parentClsNode",
".",
"attributes",
"[",
"'objtype'",
"]",
"==",
"'class'",
"assert",
"parentClsNode",
".",
"attributes",
"[",
"'do... | Generate html elements and schematic json | [
"Generate",
"html",
"elements",
"and",
"schematic",
"json"
] | 3aee09f467be74433ae2a6b2de55c6b90e5920ae | https://github.com/Nic30/sphinx-hwt/blob/3aee09f467be74433ae2a6b2de55c6b90e5920ae/sphinx_hwt/sphinx_hwt.py#L94-L155 | train | 49,747 |
Nic30/sphinx-hwt | setup.py | build_npm.run | def run(self):
has_npm = npm_installation_check()
if has_npm:
run_npm_install()
else:
print("Warning: npm not installed using prebuilded js files!",
file=sys.stderr)
"""
Download npm packages required by package.json and extract required
files from them
"""
for js in JS_FILES:
downloaded_js_name = os.path.join(TOP_DIR, js)
installed_js_name = os.path.join(TOP_DIR, "sphinx_hwt", "html", js)
if has_npm:
assert os.path.exists(downloaded_js_name), downloaded_js_name
os.makedirs(os.path.dirname(installed_js_name), exist_ok=True)
copyfile(downloaded_js_name, installed_js_name)
print("copy generated from NPM packages", installed_js_name)
else:
if os.path.exists(installed_js_name):
print("using prebuilded", installed_js_name)
else:
raise Exception("Can not find npm,"
" which is required for the installation "
"and this is pacpage has not js prebuilded") | python | def run(self):
has_npm = npm_installation_check()
if has_npm:
run_npm_install()
else:
print("Warning: npm not installed using prebuilded js files!",
file=sys.stderr)
"""
Download npm packages required by package.json and extract required
files from them
"""
for js in JS_FILES:
downloaded_js_name = os.path.join(TOP_DIR, js)
installed_js_name = os.path.join(TOP_DIR, "sphinx_hwt", "html", js)
if has_npm:
assert os.path.exists(downloaded_js_name), downloaded_js_name
os.makedirs(os.path.dirname(installed_js_name), exist_ok=True)
copyfile(downloaded_js_name, installed_js_name)
print("copy generated from NPM packages", installed_js_name)
else:
if os.path.exists(installed_js_name):
print("using prebuilded", installed_js_name)
else:
raise Exception("Can not find npm,"
" which is required for the installation "
"and this is pacpage has not js prebuilded") | [
"def",
"run",
"(",
"self",
")",
":",
"has_npm",
"=",
"npm_installation_check",
"(",
")",
"if",
"has_npm",
":",
"run_npm_install",
"(",
")",
"else",
":",
"print",
"(",
"\"Warning: npm not installed using prebuilded js files!\"",
",",
"file",
"=",
"sys",
".",
"std... | Download npm packages required by package.json and extract required
files from them | [
"Download",
"npm",
"packages",
"required",
"by",
"package",
".",
"json",
"and",
"extract",
"required",
"files",
"from",
"them"
] | 3aee09f467be74433ae2a6b2de55c6b90e5920ae | https://github.com/Nic30/sphinx-hwt/blob/3aee09f467be74433ae2a6b2de55c6b90e5920ae/setup.py#L81-L106 | train | 49,748 |
dfm/transit | transit/transit.py | Central.density | def density(self):
"""Stellar density in CGS units
"""
r = self.radius * _Rsun
m = self.mass * _Msun
return 0.75 * m / (np.pi * r * r * r) | python | def density(self):
"""Stellar density in CGS units
"""
r = self.radius * _Rsun
m = self.mass * _Msun
return 0.75 * m / (np.pi * r * r * r) | [
"def",
"density",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"radius",
"*",
"_Rsun",
"m",
"=",
"self",
".",
"mass",
"*",
"_Msun",
"return",
"0.75",
"*",
"m",
"/",
"(",
"np",
".",
"pi",
"*",
"r",
"*",
"r",
"*",
"r",
")"
] | Stellar density in CGS units | [
"Stellar",
"density",
"in",
"CGS",
"units"
] | 482d99b506657fa3fd54a388f9c6be13b9e57bce | https://github.com/dfm/transit/blob/482d99b506657fa3fd54a388f9c6be13b9e57bce/transit/transit.py#L101-L106 | train | 49,749 |
pytroll/posttroll | posttroll/__init__.py | get_context | def get_context():
"""Provide the context to use.
This function takes care of creating new contexts in case of forks.
"""
pid = os.getpid()
if pid not in context:
context[pid] = zmq.Context()
logger.debug('renewed context for PID %d', pid)
return context[pid] | python | def get_context():
"""Provide the context to use.
This function takes care of creating new contexts in case of forks.
"""
pid = os.getpid()
if pid not in context:
context[pid] = zmq.Context()
logger.debug('renewed context for PID %d', pid)
return context[pid] | [
"def",
"get_context",
"(",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"if",
"pid",
"not",
"in",
"context",
":",
"context",
"[",
"pid",
"]",
"=",
"zmq",
".",
"Context",
"(",
")",
"logger",
".",
"debug",
"(",
"'renewed context for PID %d'",
"... | Provide the context to use.
This function takes care of creating new contexts in case of forks. | [
"Provide",
"the",
"context",
"to",
"use",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/__init__.py#L37-L46 | train | 49,750 |
pytroll/posttroll | posttroll/__init__.py | strp_isoformat | def strp_isoformat(strg):
"""Decode an ISO formatted string to a datetime object.
Allow a time-string without microseconds.
We handle input like: 2011-11-14T12:51:25.123456
"""
if isinstance(strg, datetime):
return strg
if len(strg) < 19 or len(strg) > 26:
if len(strg) > 30:
strg = strg[:30] + '...'
raise ValueError("Invalid ISO formatted time string '%s'"%strg)
if strg.find(".") == -1:
strg += '.000000'
if sys.version[0:3] >= '2.6':
return datetime.strptime(strg, "%Y-%m-%dT%H:%M:%S.%f")
else:
dat, mis = strg.split(".")
dat = datetime.strptime(dat, "%Y-%m-%dT%H:%M:%S")
mis = int(float('.' + mis)*1000000)
return dat.replace(microsecond=mis) | python | def strp_isoformat(strg):
"""Decode an ISO formatted string to a datetime object.
Allow a time-string without microseconds.
We handle input like: 2011-11-14T12:51:25.123456
"""
if isinstance(strg, datetime):
return strg
if len(strg) < 19 or len(strg) > 26:
if len(strg) > 30:
strg = strg[:30] + '...'
raise ValueError("Invalid ISO formatted time string '%s'"%strg)
if strg.find(".") == -1:
strg += '.000000'
if sys.version[0:3] >= '2.6':
return datetime.strptime(strg, "%Y-%m-%dT%H:%M:%S.%f")
else:
dat, mis = strg.split(".")
dat = datetime.strptime(dat, "%Y-%m-%dT%H:%M:%S")
mis = int(float('.' + mis)*1000000)
return dat.replace(microsecond=mis) | [
"def",
"strp_isoformat",
"(",
"strg",
")",
":",
"if",
"isinstance",
"(",
"strg",
",",
"datetime",
")",
":",
"return",
"strg",
"if",
"len",
"(",
"strg",
")",
"<",
"19",
"or",
"len",
"(",
"strg",
")",
">",
"26",
":",
"if",
"len",
"(",
"strg",
")",
... | Decode an ISO formatted string to a datetime object.
Allow a time-string without microseconds.
We handle input like: 2011-11-14T12:51:25.123456 | [
"Decode",
"an",
"ISO",
"formatted",
"string",
"to",
"a",
"datetime",
"object",
".",
"Allow",
"a",
"time",
"-",
"string",
"without",
"microseconds",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/__init__.py#L49-L69 | train | 49,751 |
Clinical-Genomics/trailblazer | trailblazer/store/api.py | BaseHandler.find_analysis | def find_analysis(self, family, started_at, status):
"""Find a single analysis."""
query = self.Analysis.query.filter_by(
family=family,
started_at=started_at,
status=status,
)
return query.first() | python | def find_analysis(self, family, started_at, status):
"""Find a single analysis."""
query = self.Analysis.query.filter_by(
family=family,
started_at=started_at,
status=status,
)
return query.first() | [
"def",
"find_analysis",
"(",
"self",
",",
"family",
",",
"started_at",
",",
"status",
")",
":",
"query",
"=",
"self",
".",
"Analysis",
".",
"query",
".",
"filter_by",
"(",
"family",
"=",
"family",
",",
"started_at",
"=",
"started_at",
",",
"status",
"=",... | Find a single analysis. | [
"Find",
"a",
"single",
"analysis",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/store/api.py#L26-L33 | train | 49,752 |
Clinical-Genomics/trailblazer | trailblazer/store/api.py | BaseHandler.analyses | def analyses(self, *, family: str=None, query: str=None, status: str=None, deleted: bool=None,
temp: bool=False, before: dt.datetime=None, is_visible: bool=None):
"""Fetch analyses form the database."""
analysis_query = self.Analysis.query
if family:
analysis_query = analysis_query.filter_by(family=family)
elif query:
analysis_query = analysis_query.filter(sqa.or_(
self.Analysis.family.like(f"%{query}%"),
self.Analysis.status.like(f"%{query}%"),
))
if status:
analysis_query = analysis_query.filter_by(status=status)
if isinstance(deleted, bool):
analysis_query = analysis_query.filter_by(is_deleted=deleted)
if temp:
analysis_query = analysis_query.filter(self.Analysis.status.in_(TEMP_STATUSES))
if before:
analysis_query = analysis_query.filter(self.Analysis.started_at < before)
if is_visible is not None:
analysis_query = analysis_query.filter_by(is_visible=is_visible)
return analysis_query.order_by(self.Analysis.started_at.desc()) | python | def analyses(self, *, family: str=None, query: str=None, status: str=None, deleted: bool=None,
temp: bool=False, before: dt.datetime=None, is_visible: bool=None):
"""Fetch analyses form the database."""
analysis_query = self.Analysis.query
if family:
analysis_query = analysis_query.filter_by(family=family)
elif query:
analysis_query = analysis_query.filter(sqa.or_(
self.Analysis.family.like(f"%{query}%"),
self.Analysis.status.like(f"%{query}%"),
))
if status:
analysis_query = analysis_query.filter_by(status=status)
if isinstance(deleted, bool):
analysis_query = analysis_query.filter_by(is_deleted=deleted)
if temp:
analysis_query = analysis_query.filter(self.Analysis.status.in_(TEMP_STATUSES))
if before:
analysis_query = analysis_query.filter(self.Analysis.started_at < before)
if is_visible is not None:
analysis_query = analysis_query.filter_by(is_visible=is_visible)
return analysis_query.order_by(self.Analysis.started_at.desc()) | [
"def",
"analyses",
"(",
"self",
",",
"*",
",",
"family",
":",
"str",
"=",
"None",
",",
"query",
":",
"str",
"=",
"None",
",",
"status",
":",
"str",
"=",
"None",
",",
"deleted",
":",
"bool",
"=",
"None",
",",
"temp",
":",
"bool",
"=",
"False",
"... | Fetch analyses form the database. | [
"Fetch",
"analyses",
"form",
"the",
"database",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/store/api.py#L35-L56 | train | 49,753 |
Clinical-Genomics/trailblazer | trailblazer/store/api.py | BaseHandler.analysis | def analysis(self, analysis_id: int) -> models.Analysis:
"""Get a single analysis."""
return self.Analysis.query.get(analysis_id) | python | def analysis(self, analysis_id: int) -> models.Analysis:
"""Get a single analysis."""
return self.Analysis.query.get(analysis_id) | [
"def",
"analysis",
"(",
"self",
",",
"analysis_id",
":",
"int",
")",
"->",
"models",
".",
"Analysis",
":",
"return",
"self",
".",
"Analysis",
".",
"query",
".",
"get",
"(",
"analysis_id",
")"
] | Get a single analysis. | [
"Get",
"a",
"single",
"analysis",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/store/api.py#L58-L60 | train | 49,754 |
Clinical-Genomics/trailblazer | trailblazer/store/api.py | BaseHandler.track_update | def track_update(self):
"""Update the lastest updated date in the database."""
metadata = self.info()
metadata.updated_at = dt.datetime.now()
self.commit() | python | def track_update(self):
"""Update the lastest updated date in the database."""
metadata = self.info()
metadata.updated_at = dt.datetime.now()
self.commit() | [
"def",
"track_update",
"(",
"self",
")",
":",
"metadata",
"=",
"self",
".",
"info",
"(",
")",
"metadata",
".",
"updated_at",
"=",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"commit",
"(",
")"
] | Update the lastest updated date in the database. | [
"Update",
"the",
"lastest",
"updated",
"date",
"in",
"the",
"database",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/store/api.py#L62-L66 | train | 49,755 |
Clinical-Genomics/trailblazer | trailblazer/store/api.py | BaseHandler.add_pending | def add_pending(self, family: str, email: str=None) -> models.Analysis:
"""Add pending entry for an analysis."""
started_at = dt.datetime.now()
new_log = self.Analysis(family=family, status='pending', started_at=started_at)
new_log.user = self.user(email) if email else None
self.add_commit(new_log)
return new_log | python | def add_pending(self, family: str, email: str=None) -> models.Analysis:
"""Add pending entry for an analysis."""
started_at = dt.datetime.now()
new_log = self.Analysis(family=family, status='pending', started_at=started_at)
new_log.user = self.user(email) if email else None
self.add_commit(new_log)
return new_log | [
"def",
"add_pending",
"(",
"self",
",",
"family",
":",
"str",
",",
"email",
":",
"str",
"=",
"None",
")",
"->",
"models",
".",
"Analysis",
":",
"started_at",
"=",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
"new_log",
"=",
"self",
".",
"Analysis",
... | Add pending entry for an analysis. | [
"Add",
"pending",
"entry",
"for",
"an",
"analysis",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/store/api.py#L77-L83 | train | 49,756 |
Clinical-Genomics/trailblazer | trailblazer/store/api.py | BaseHandler.add_user | def add_user(self, name: str, email: str) -> models.User:
"""Add a new user to the database."""
new_user = self.User(name=name, email=email)
self.add_commit(new_user)
return new_user | python | def add_user(self, name: str, email: str) -> models.User:
"""Add a new user to the database."""
new_user = self.User(name=name, email=email)
self.add_commit(new_user)
return new_user | [
"def",
"add_user",
"(",
"self",
",",
"name",
":",
"str",
",",
"email",
":",
"str",
")",
"->",
"models",
".",
"User",
":",
"new_user",
"=",
"self",
".",
"User",
"(",
"name",
"=",
"name",
",",
"email",
"=",
"email",
")",
"self",
".",
"add_commit",
... | Add a new user to the database. | [
"Add",
"a",
"new",
"user",
"to",
"the",
"database",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/store/api.py#L85-L89 | train | 49,757 |
Clinical-Genomics/trailblazer | trailblazer/store/api.py | BaseHandler.user | def user(self, email: str) -> models.User:
"""Fetch a user from the database."""
return self.User.query.filter_by(email=email).first() | python | def user(self, email: str) -> models.User:
"""Fetch a user from the database."""
return self.User.query.filter_by(email=email).first() | [
"def",
"user",
"(",
"self",
",",
"email",
":",
"str",
")",
"->",
"models",
".",
"User",
":",
"return",
"self",
".",
"User",
".",
"query",
".",
"filter_by",
"(",
"email",
"=",
"email",
")",
".",
"first",
"(",
")"
] | Fetch a user from the database. | [
"Fetch",
"a",
"user",
"from",
"the",
"database",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/store/api.py#L91-L93 | train | 49,758 |
pytroll/posttroll | posttroll/address_receiver.py | AddressReceiver.start | def start(self):
"""Start the receiver.
"""
if not self._is_running:
self._do_run = True
self._thread.start()
return self | python | def start(self):
"""Start the receiver.
"""
if not self._is_running:
self._do_run = True
self._thread.start()
return self | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_running",
":",
"self",
".",
"_do_run",
"=",
"True",
"self",
".",
"_thread",
".",
"start",
"(",
")",
"return",
"self"
] | Start the receiver. | [
"Start",
"the",
"receiver",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/address_receiver.py#L80-L86 | train | 49,759 |
pytroll/posttroll | posttroll/address_receiver.py | AddressReceiver._check_age | def _check_age(self, pub, min_interval=timedelta(seconds=0)):
"""Check the age of the receiver.
"""
now = datetime.utcnow()
if (now - self._last_age_check) <= min_interval:
return
LOGGER.debug("%s - checking addresses", str(datetime.utcnow()))
self._last_age_check = now
to_del = []
with self._address_lock:
for addr, metadata in self._addresses.items():
atime = metadata["receive_time"]
if now - atime > self._max_age:
mda = {'status': False,
'URI': addr,
'service': metadata['service']}
msg = Message('/address/' + metadata['name'], 'info', mda)
to_del.append(addr)
LOGGER.info("publish remove '%s'", str(msg))
pub.send(msg.encode())
for addr in to_del:
del self._addresses[addr] | python | def _check_age(self, pub, min_interval=timedelta(seconds=0)):
"""Check the age of the receiver.
"""
now = datetime.utcnow()
if (now - self._last_age_check) <= min_interval:
return
LOGGER.debug("%s - checking addresses", str(datetime.utcnow()))
self._last_age_check = now
to_del = []
with self._address_lock:
for addr, metadata in self._addresses.items():
atime = metadata["receive_time"]
if now - atime > self._max_age:
mda = {'status': False,
'URI': addr,
'service': metadata['service']}
msg = Message('/address/' + metadata['name'], 'info', mda)
to_del.append(addr)
LOGGER.info("publish remove '%s'", str(msg))
pub.send(msg.encode())
for addr in to_del:
del self._addresses[addr] | [
"def",
"_check_age",
"(",
"self",
",",
"pub",
",",
"min_interval",
"=",
"timedelta",
"(",
"seconds",
"=",
"0",
")",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"(",
"now",
"-",
"self",
".",
"_last_age_check",
")",
"<=",
"min_inte... | Check the age of the receiver. | [
"Check",
"the",
"age",
"of",
"the",
"receiver",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/address_receiver.py#L114-L136 | train | 49,760 |
pytroll/posttroll | posttroll/address_receiver.py | AddressReceiver._run | def _run(self):
"""Run the receiver.
"""
port = broadcast_port
nameservers = []
if self._multicast_enabled:
recv = MulticastReceiver(port).settimeout(2.)
while True:
try:
recv = MulticastReceiver(port).settimeout(2.)
LOGGER.info("Receiver initialized.")
break
except IOError as err:
if err.errno == errno.ENODEV:
LOGGER.error("Receiver initialization failed "
"(no such device). "
"Trying again in %d s",
10)
time.sleep(10)
else:
raise
else:
recv = _SimpleReceiver(port)
nameservers = ["localhost"]
self._is_running = True
with Publish("address_receiver", self._port, ["addresses"],
nameservers=nameservers) as pub:
try:
while self._do_run:
try:
data, fromaddr = recv()
LOGGER.debug("data %s", data)
del fromaddr
except SocketTimeout:
if self._multicast_enabled:
LOGGER.debug("Multicast socket timed out on recv!")
continue
finally:
self._check_age(pub, min_interval=self._max_age / 20)
if self._do_heartbeat:
pub.heartbeat(min_interval=29)
msg = Message.decode(data)
name = msg.subject.split("/")[1]
if(msg.type == 'info' and
msg.subject.lower().startswith(self._subject)):
addr = msg.data["URI"]
msg.data['status'] = True
metadata = copy.copy(msg.data)
metadata["name"] = name
LOGGER.debug('receiving address %s %s %s', str(addr),
str(name), str(metadata))
if addr not in self._addresses:
LOGGER.info("nameserver: publish add '%s'",
str(msg))
pub.send(msg.encode())
self._add(addr, metadata)
finally:
self._is_running = False
recv.close() | python | def _run(self):
"""Run the receiver.
"""
port = broadcast_port
nameservers = []
if self._multicast_enabled:
recv = MulticastReceiver(port).settimeout(2.)
while True:
try:
recv = MulticastReceiver(port).settimeout(2.)
LOGGER.info("Receiver initialized.")
break
except IOError as err:
if err.errno == errno.ENODEV:
LOGGER.error("Receiver initialization failed "
"(no such device). "
"Trying again in %d s",
10)
time.sleep(10)
else:
raise
else:
recv = _SimpleReceiver(port)
nameservers = ["localhost"]
self._is_running = True
with Publish("address_receiver", self._port, ["addresses"],
nameservers=nameservers) as pub:
try:
while self._do_run:
try:
data, fromaddr = recv()
LOGGER.debug("data %s", data)
del fromaddr
except SocketTimeout:
if self._multicast_enabled:
LOGGER.debug("Multicast socket timed out on recv!")
continue
finally:
self._check_age(pub, min_interval=self._max_age / 20)
if self._do_heartbeat:
pub.heartbeat(min_interval=29)
msg = Message.decode(data)
name = msg.subject.split("/")[1]
if(msg.type == 'info' and
msg.subject.lower().startswith(self._subject)):
addr = msg.data["URI"]
msg.data['status'] = True
metadata = copy.copy(msg.data)
metadata["name"] = name
LOGGER.debug('receiving address %s %s %s', str(addr),
str(name), str(metadata))
if addr not in self._addresses:
LOGGER.info("nameserver: publish add '%s'",
str(msg))
pub.send(msg.encode())
self._add(addr, metadata)
finally:
self._is_running = False
recv.close() | [
"def",
"_run",
"(",
"self",
")",
":",
"port",
"=",
"broadcast_port",
"nameservers",
"=",
"[",
"]",
"if",
"self",
".",
"_multicast_enabled",
":",
"recv",
"=",
"MulticastReceiver",
"(",
"port",
")",
".",
"settimeout",
"(",
"2.",
")",
"while",
"True",
":",
... | Run the receiver. | [
"Run",
"the",
"receiver",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/address_receiver.py#L138-L198 | train | 49,761 |
pytroll/posttroll | posttroll/address_receiver.py | AddressReceiver._add | def _add(self, adr, metadata):
"""Add an address.
"""
with self._address_lock:
metadata["receive_time"] = datetime.utcnow()
self._addresses[adr] = metadata | python | def _add(self, adr, metadata):
"""Add an address.
"""
with self._address_lock:
metadata["receive_time"] = datetime.utcnow()
self._addresses[adr] = metadata | [
"def",
"_add",
"(",
"self",
",",
"adr",
",",
"metadata",
")",
":",
"with",
"self",
".",
"_address_lock",
":",
"metadata",
"[",
"\"receive_time\"",
"]",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"self",
".",
"_addresses",
"[",
"adr",
"]",
"=",
"metadata... | Add an address. | [
"Add",
"an",
"address",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/address_receiver.py#L200-L205 | train | 49,762 |
phoemur/wgetter | wgetter.py | get_console_width | def get_console_width():
"""Return width of available window area. Autodetection works for
Windows and POSIX platforms. Returns 80 for others
Code from http://bitbucket.org/techtonik/python-pager
"""
if os.name == 'nt':
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
# get console handle
from ctypes import windll, Structure, byref
try:
from ctypes.wintypes import SHORT, WORD, DWORD
except ImportError:
# workaround for missing types in Python 2.5
from ctypes import (
c_short as SHORT, c_ushort as WORD, c_ulong as DWORD)
console_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# CONSOLE_SCREEN_BUFFER_INFO Structure
class COORD(Structure):
_fields_ = [("X", SHORT), ("Y", SHORT)]
class SMALL_RECT(Structure):
_fields_ = [("Left", SHORT), ("Top", SHORT),
("Right", SHORT), ("Bottom", SHORT)]
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
_fields_ = [("dwSize", COORD),
("dwCursorPosition", COORD),
("wAttributes", WORD),
("srWindow", SMALL_RECT),
("dwMaximumWindowSize", DWORD)]
sbi = CONSOLE_SCREEN_BUFFER_INFO()
ret = windll.kernel32.GetConsoleScreenBufferInfo(
console_handle, byref(sbi))
if ret == 0:
return 0
return sbi.srWindow.Right + 1
elif os.name == 'posix':
from fcntl import ioctl
from termios import TIOCGWINSZ
from array import array
winsize = array("H", [0] * 4)
try:
ioctl(sys.stdout.fileno(), TIOCGWINSZ, winsize)
except IOError:
pass
return (winsize[1], winsize[0])[0]
return 80 | python | def get_console_width():
"""Return width of available window area. Autodetection works for
Windows and POSIX platforms. Returns 80 for others
Code from http://bitbucket.org/techtonik/python-pager
"""
if os.name == 'nt':
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
# get console handle
from ctypes import windll, Structure, byref
try:
from ctypes.wintypes import SHORT, WORD, DWORD
except ImportError:
# workaround for missing types in Python 2.5
from ctypes import (
c_short as SHORT, c_ushort as WORD, c_ulong as DWORD)
console_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# CONSOLE_SCREEN_BUFFER_INFO Structure
class COORD(Structure):
_fields_ = [("X", SHORT), ("Y", SHORT)]
class SMALL_RECT(Structure):
_fields_ = [("Left", SHORT), ("Top", SHORT),
("Right", SHORT), ("Bottom", SHORT)]
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
_fields_ = [("dwSize", COORD),
("dwCursorPosition", COORD),
("wAttributes", WORD),
("srWindow", SMALL_RECT),
("dwMaximumWindowSize", DWORD)]
sbi = CONSOLE_SCREEN_BUFFER_INFO()
ret = windll.kernel32.GetConsoleScreenBufferInfo(
console_handle, byref(sbi))
if ret == 0:
return 0
return sbi.srWindow.Right + 1
elif os.name == 'posix':
from fcntl import ioctl
from termios import TIOCGWINSZ
from array import array
winsize = array("H", [0] * 4)
try:
ioctl(sys.stdout.fileno(), TIOCGWINSZ, winsize)
except IOError:
pass
return (winsize[1], winsize[0])[0]
return 80 | [
"def",
"get_console_width",
"(",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"STD_INPUT_HANDLE",
"=",
"-",
"10",
"STD_OUTPUT_HANDLE",
"=",
"-",
"11",
"STD_ERROR_HANDLE",
"=",
"-",
"12",
"# get console handle",
"from",
"ctypes",
"import",
"windll",
... | Return width of available window area. Autodetection works for
Windows and POSIX platforms. Returns 80 for others
Code from http://bitbucket.org/techtonik/python-pager | [
"Return",
"width",
"of",
"available",
"window",
"area",
".",
"Autodetection",
"works",
"for",
"Windows",
"and",
"POSIX",
"platforms",
".",
"Returns",
"80",
"for",
"others"
] | ac182a72480e150e4a800fbade4fbccc29e72b51 | https://github.com/phoemur/wgetter/blob/ac182a72480e150e4a800fbade4fbccc29e72b51/wgetter.py#L69-L125 | train | 49,763 |
phoemur/wgetter | wgetter.py | report_bar | def report_bar(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used to print the download bar
'''
percent = int(bytes_so_far * 100 / total_size)
current = approximate_size(bytes_so_far).center(9)
total = approximate_size(total_size).center(9)
shaded = int(float(bytes_so_far) / total_size * AVAIL_WIDTH)
sys.stdout.write(
" {0}% [{1}{2}{3}] {4}/{5} {6} eta{7}".format(str(percent).center(4),
'=' * (shaded - 1),
'>',
' ' * (AVAIL_WIDTH - shaded),
current,
total,
(approximate_size(speed) + '/s').center(11),
eta.center(10)))
sys.stdout.write("\r")
sys.stdout.flush() | python | def report_bar(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used to print the download bar
'''
percent = int(bytes_so_far * 100 / total_size)
current = approximate_size(bytes_so_far).center(9)
total = approximate_size(total_size).center(9)
shaded = int(float(bytes_so_far) / total_size * AVAIL_WIDTH)
sys.stdout.write(
" {0}% [{1}{2}{3}] {4}/{5} {6} eta{7}".format(str(percent).center(4),
'=' * (shaded - 1),
'>',
' ' * (AVAIL_WIDTH - shaded),
current,
total,
(approximate_size(speed) + '/s').center(11),
eta.center(10)))
sys.stdout.write("\r")
sys.stdout.flush() | [
"def",
"report_bar",
"(",
"bytes_so_far",
",",
"total_size",
",",
"speed",
",",
"eta",
")",
":",
"percent",
"=",
"int",
"(",
"bytes_so_far",
"*",
"100",
"/",
"total_size",
")",
"current",
"=",
"approximate_size",
"(",
"bytes_so_far",
")",
".",
"center",
"(... | This callback for the download function is used to print the download bar | [
"This",
"callback",
"for",
"the",
"download",
"function",
"is",
"used",
"to",
"print",
"the",
"download",
"bar"
] | ac182a72480e150e4a800fbade4fbccc29e72b51 | https://github.com/phoemur/wgetter/blob/ac182a72480e150e4a800fbade4fbccc29e72b51/wgetter.py#L190-L208 | train | 49,764 |
phoemur/wgetter | wgetter.py | report_unknown | def report_unknown(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used
when the total size is unknown
'''
sys.stdout.write(
"Downloading: {0} / Unknown - {1}/s ".format(approximate_size(bytes_so_far),
approximate_size(speed)))
sys.stdout.write("\r")
sys.stdout.flush() | python | def report_unknown(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used
when the total size is unknown
'''
sys.stdout.write(
"Downloading: {0} / Unknown - {1}/s ".format(approximate_size(bytes_so_far),
approximate_size(speed)))
sys.stdout.write("\r")
sys.stdout.flush() | [
"def",
"report_unknown",
"(",
"bytes_so_far",
",",
"total_size",
",",
"speed",
",",
"eta",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"Downloading: {0} / Unknown - {1}/s \"",
".",
"format",
"(",
"approximate_size",
"(",
"bytes_so_far",
")",
",",
"... | This callback for the download function is used
when the total size is unknown | [
"This",
"callback",
"for",
"the",
"download",
"function",
"is",
"used",
"when",
"the",
"total",
"size",
"is",
"unknown"
] | ac182a72480e150e4a800fbade4fbccc29e72b51 | https://github.com/phoemur/wgetter/blob/ac182a72480e150e4a800fbade4fbccc29e72b51/wgetter.py#L211-L221 | train | 49,765 |
phoemur/wgetter | wgetter.py | report_onlysize | def report_onlysize(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used when console width
is not enough to print the bar.
It prints only the sizes
'''
percent = int(bytes_so_far * 100 / total_size)
current = approximate_size(bytes_so_far).center(10)
total = approximate_size(total_size).center(10)
sys.stdout.write('D: {0}% -{1}/{2}'.format(percent, current, total) + "eta {0}".format(eta))
sys.stdout.write("\r")
sys.stdout.flush() | python | def report_onlysize(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used when console width
is not enough to print the bar.
It prints only the sizes
'''
percent = int(bytes_so_far * 100 / total_size)
current = approximate_size(bytes_so_far).center(10)
total = approximate_size(total_size).center(10)
sys.stdout.write('D: {0}% -{1}/{2}'.format(percent, current, total) + "eta {0}".format(eta))
sys.stdout.write("\r")
sys.stdout.flush() | [
"def",
"report_onlysize",
"(",
"bytes_so_far",
",",
"total_size",
",",
"speed",
",",
"eta",
")",
":",
"percent",
"=",
"int",
"(",
"bytes_so_far",
"*",
"100",
"/",
"total_size",
")",
"current",
"=",
"approximate_size",
"(",
"bytes_so_far",
")",
".",
"center",... | This callback for the download function is used when console width
is not enough to print the bar.
It prints only the sizes | [
"This",
"callback",
"for",
"the",
"download",
"function",
"is",
"used",
"when",
"console",
"width",
"is",
"not",
"enough",
"to",
"print",
"the",
"bar",
".",
"It",
"prints",
"only",
"the",
"sizes"
] | ac182a72480e150e4a800fbade4fbccc29e72b51 | https://github.com/phoemur/wgetter/blob/ac182a72480e150e4a800fbade4fbccc29e72b51/wgetter.py#L224-L235 | train | 49,766 |
Clinical-Genomics/trailblazer | trailblazer/cli/ls.py | ls_cmd | def ls_cmd(context, before, status):
"""Display recent logs for analyses."""
runs = context.obj['store'].analyses(
status=status,
deleted=False,
before=parse_date(before) if before else None,
).limit(30)
for run_obj in runs:
if run_obj.status == 'pending':
message = f"{run_obj.id} | {run_obj.family} [{run_obj.status.upper()}]"
else:
message = (f"{run_obj.id} | {run_obj.family} {run_obj.started_at.date()} "
f"[{run_obj.type.upper()}/{run_obj.status.upper()}]")
if run_obj.status == 'running':
message = click.style(f"{message} - {run_obj.progress * 100}/100", fg='blue')
elif run_obj.status == 'completed':
message = click.style(f"{message} - {run_obj.completed_at}", fg='green')
elif run_obj.status == 'failed':
message = click.style(message, fg='red')
print(message) | python | def ls_cmd(context, before, status):
"""Display recent logs for analyses."""
runs = context.obj['store'].analyses(
status=status,
deleted=False,
before=parse_date(before) if before else None,
).limit(30)
for run_obj in runs:
if run_obj.status == 'pending':
message = f"{run_obj.id} | {run_obj.family} [{run_obj.status.upper()}]"
else:
message = (f"{run_obj.id} | {run_obj.family} {run_obj.started_at.date()} "
f"[{run_obj.type.upper()}/{run_obj.status.upper()}]")
if run_obj.status == 'running':
message = click.style(f"{message} - {run_obj.progress * 100}/100", fg='blue')
elif run_obj.status == 'completed':
message = click.style(f"{message} - {run_obj.completed_at}", fg='green')
elif run_obj.status == 'failed':
message = click.style(message, fg='red')
print(message) | [
"def",
"ls_cmd",
"(",
"context",
",",
"before",
",",
"status",
")",
":",
"runs",
"=",
"context",
".",
"obj",
"[",
"'store'",
"]",
".",
"analyses",
"(",
"status",
"=",
"status",
",",
"deleted",
"=",
"False",
",",
"before",
"=",
"parse_date",
"(",
"bef... | Display recent logs for analyses. | [
"Display",
"recent",
"logs",
"for",
"analyses",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/cli/ls.py#L11-L30 | train | 49,767 |
ozgurgunes/django-manifest | manifest/core/templatetags/analytics.py | analytics | def analytics(account=None, *args, **kwargs):
"""
Simple Google Analytics integration.
First looks for an ``account`` parameter. If not supplied, uses
Django ``GOOGLE_ANALYTICS_ACCOUNT`` setting. If account not set,
raises ``TemplateSyntaxError``.
:param account:
Google Analytics account id to be used.
"""
if not account:
try:
account = settings.GOOGLE_ANALYTICS_ACCOUNT
except:
raise template.TemplateSyntaxError(
"Analytics account could not found either "
"in tag parameters or settings")
return {'account': account, 'params':kwargs } | python | def analytics(account=None, *args, **kwargs):
"""
Simple Google Analytics integration.
First looks for an ``account`` parameter. If not supplied, uses
Django ``GOOGLE_ANALYTICS_ACCOUNT`` setting. If account not set,
raises ``TemplateSyntaxError``.
:param account:
Google Analytics account id to be used.
"""
if not account:
try:
account = settings.GOOGLE_ANALYTICS_ACCOUNT
except:
raise template.TemplateSyntaxError(
"Analytics account could not found either "
"in tag parameters or settings")
return {'account': account, 'params':kwargs } | [
"def",
"analytics",
"(",
"account",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"account",
":",
"try",
":",
"account",
"=",
"settings",
".",
"GOOGLE_ANALYTICS_ACCOUNT",
"except",
":",
"raise",
"template",
".",
"Template... | Simple Google Analytics integration.
First looks for an ``account`` parameter. If not supplied, uses
Django ``GOOGLE_ANALYTICS_ACCOUNT`` setting. If account not set,
raises ``TemplateSyntaxError``.
:param account:
Google Analytics account id to be used. | [
"Simple",
"Google",
"Analytics",
"integration",
"."
] | 9873bbf2a475b76284ad7e36b2b26c92131e72dd | https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/core/templatetags/analytics.py#L8-L27 | train | 49,768 |
Clinical-Genomics/trailblazer | trailblazer/server/api.py | analyses | def analyses():
"""Display analyses."""
per_page = int(request.args.get('per_page', 50))
page = int(request.args.get('page', 1))
query = store.analyses(status=request.args.get('status'),
query=request.args.get('query'),
is_visible=request.args.get('is_visible') == 'true' or None)
query_page = query.paginate(page, per_page=per_page)
data = []
for analysis_obj in query_page.items:
analysis_data = analysis_obj.to_dict()
analysis_data['user'] = analysis_obj.user.to_dict() if analysis_obj.user else None
analysis_data['failed_jobs'] = [job_obj.to_dict() for job_obj in analysis_obj.failed_jobs]
data.append(analysis_data)
return jsonify(analyses=data) | python | def analyses():
"""Display analyses."""
per_page = int(request.args.get('per_page', 50))
page = int(request.args.get('page', 1))
query = store.analyses(status=request.args.get('status'),
query=request.args.get('query'),
is_visible=request.args.get('is_visible') == 'true' or None)
query_page = query.paginate(page, per_page=per_page)
data = []
for analysis_obj in query_page.items:
analysis_data = analysis_obj.to_dict()
analysis_data['user'] = analysis_obj.user.to_dict() if analysis_obj.user else None
analysis_data['failed_jobs'] = [job_obj.to_dict() for job_obj in analysis_obj.failed_jobs]
data.append(analysis_data)
return jsonify(analyses=data) | [
"def",
"analyses",
"(",
")",
":",
"per_page",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'per_page'",
",",
"50",
")",
")",
"page",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'page'",
",",
"1",
")",
")",
"query",
... | Display analyses. | [
"Display",
"analyses",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/server/api.py#L27-L43 | train | 49,769 |
Clinical-Genomics/trailblazer | trailblazer/server/api.py | analysis | def analysis(analysis_id):
"""Display a single analysis."""
analysis_obj = store.analysis(analysis_id)
if analysis_obj is None:
return abort(404)
if request.method == 'PUT':
analysis_obj.update(request.json)
store.commit()
data = analysis_obj.to_dict()
data['failed_jobs'] = [job_obj.to_dict() for job_obj in analysis_obj.failed_jobs]
data['user'] = analysis_obj.user.to_dict() if analysis_obj.user else None
return jsonify(**data) | python | def analysis(analysis_id):
"""Display a single analysis."""
analysis_obj = store.analysis(analysis_id)
if analysis_obj is None:
return abort(404)
if request.method == 'PUT':
analysis_obj.update(request.json)
store.commit()
data = analysis_obj.to_dict()
data['failed_jobs'] = [job_obj.to_dict() for job_obj in analysis_obj.failed_jobs]
data['user'] = analysis_obj.user.to_dict() if analysis_obj.user else None
return jsonify(**data) | [
"def",
"analysis",
"(",
"analysis_id",
")",
":",
"analysis_obj",
"=",
"store",
".",
"analysis",
"(",
"analysis_id",
")",
"if",
"analysis_obj",
"is",
"None",
":",
"return",
"abort",
"(",
"404",
")",
"if",
"request",
".",
"method",
"==",
"'PUT'",
":",
"ana... | Display a single analysis. | [
"Display",
"a",
"single",
"analysis",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/server/api.py#L47-L60 | train | 49,770 |
ozgurgunes/django-manifest | manifest/accounts/utils.py | get_datetime_now | def get_datetime_now():
"""
Returns datetime object with current point in time.
In Django 1.4+ it uses Django's django.utils.timezone.now() which returns
an aware or naive datetime that represents the current point in time
when ``USE_TZ`` in project's settings is True or False respectively.
In older versions of Django it uses datetime.datetime.now().
"""
try:
from django.utils import timezone
return timezone.now()
except ImportError:
return datetime.datetime.now() | python | def get_datetime_now():
"""
Returns datetime object with current point in time.
In Django 1.4+ it uses Django's django.utils.timezone.now() which returns
an aware or naive datetime that represents the current point in time
when ``USE_TZ`` in project's settings is True or False respectively.
In older versions of Django it uses datetime.datetime.now().
"""
try:
from django.utils import timezone
return timezone.now()
except ImportError:
return datetime.datetime.now() | [
"def",
"get_datetime_now",
"(",
")",
":",
"try",
":",
"from",
"django",
".",
"utils",
"import",
"timezone",
"return",
"timezone",
".",
"now",
"(",
")",
"except",
"ImportError",
":",
"return",
"datetime",
".",
"datetime",
".",
"now",
"(",
")"
] | Returns datetime object with current point in time.
In Django 1.4+ it uses Django's django.utils.timezone.now() which returns
an aware or naive datetime that represents the current point in time
when ``USE_TZ`` in project's settings is True or False respectively.
In older versions of Django it uses datetime.datetime.now(). | [
"Returns",
"datetime",
"object",
"with",
"current",
"point",
"in",
"time",
"."
] | 9873bbf2a475b76284ad7e36b2b26c92131e72dd | https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/utils.py#L113-L127 | train | 49,771 |
pytroll/posttroll | posttroll/message.py | is_valid_data | def is_valid_data(obj):
"""Check if data is JSON serializable.
"""
if obj:
try:
tmp = json.dumps(obj, default=datetime_encoder)
del tmp
except (TypeError, UnicodeDecodeError):
return False
return True | python | def is_valid_data(obj):
"""Check if data is JSON serializable.
"""
if obj:
try:
tmp = json.dumps(obj, default=datetime_encoder)
del tmp
except (TypeError, UnicodeDecodeError):
return False
return True | [
"def",
"is_valid_data",
"(",
"obj",
")",
":",
"if",
"obj",
":",
"try",
":",
"tmp",
"=",
"json",
".",
"dumps",
"(",
"obj",
",",
"default",
"=",
"datetime_encoder",
")",
"del",
"tmp",
"except",
"(",
"TypeError",
",",
"UnicodeDecodeError",
")",
":",
"retu... | Check if data is JSON serializable. | [
"Check",
"if",
"data",
"is",
"JSON",
"serializable",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L85-L94 | train | 49,772 |
pytroll/posttroll | posttroll/message.py | datetime_decoder | def datetime_decoder(dct):
"""Decode datetimes to python objects.
"""
if isinstance(dct, list):
pairs = enumerate(dct)
elif isinstance(dct, dict):
pairs = dct.items()
result = []
for key, val in pairs:
if isinstance(val, six.string_types):
try:
val = strp_isoformat(val)
except ValueError:
pass
elif isinstance(val, (dict, list)):
val = datetime_decoder(val)
result.append((key, val))
if isinstance(dct, list):
return [x[1] for x in result]
elif isinstance(dct, dict):
return dict(result) | python | def datetime_decoder(dct):
"""Decode datetimes to python objects.
"""
if isinstance(dct, list):
pairs = enumerate(dct)
elif isinstance(dct, dict):
pairs = dct.items()
result = []
for key, val in pairs:
if isinstance(val, six.string_types):
try:
val = strp_isoformat(val)
except ValueError:
pass
elif isinstance(val, (dict, list)):
val = datetime_decoder(val)
result.append((key, val))
if isinstance(dct, list):
return [x[1] for x in result]
elif isinstance(dct, dict):
return dict(result) | [
"def",
"datetime_decoder",
"(",
"dct",
")",
":",
"if",
"isinstance",
"(",
"dct",
",",
"list",
")",
":",
"pairs",
"=",
"enumerate",
"(",
"dct",
")",
"elif",
"isinstance",
"(",
"dct",
",",
"dict",
")",
":",
"pairs",
"=",
"dct",
".",
"items",
"(",
")"... | Decode datetimes to python objects. | [
"Decode",
"datetimes",
"to",
"python",
"objects",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L224-L244 | train | 49,773 |
pytroll/posttroll | posttroll/message.py | _decode | def _decode(rawstr):
"""Convert a raw string to a Message.
"""
# Check for the magick word.
try:
rawstr = rawstr.decode('utf-8')
except (AttributeError, UnicodeEncodeError):
pass
except (UnicodeDecodeError):
try:
rawstr = rawstr.decode('iso-8859-1')
except (UnicodeDecodeError):
rawstr = rawstr.decode('utf-8', 'ignore')
if not rawstr.startswith(_MAGICK):
raise MessageError("This is not a '%s' message (wrong magick word)"
% _MAGICK)
rawstr = rawstr[len(_MAGICK):]
# Check for element count and version
raw = re.split(r"\s+", rawstr, maxsplit=6)
if len(raw) < 5:
raise MessageError("Could node decode raw string: '%s ...'"
% str(rawstr[:36]))
version = raw[4][:len(_VERSION)]
if not _is_valid_version(version):
raise MessageError("Invalid Message version: '%s'" % str(version))
# Start to build message
msg = dict((('subject', raw[0].strip()),
('type', raw[1].strip()),
('sender', raw[2].strip()),
('time', strp_isoformat(raw[3].strip())),
('version', version)))
# Data part
try:
mimetype = raw[5].lower()
data = raw[6]
except IndexError:
mimetype = None
if mimetype is None:
msg['data'] = ''
msg['binary'] = False
elif mimetype == 'application/json':
try:
msg['data'] = json.loads(raw[6], object_hook=datetime_decoder)
msg['binary'] = False
except ValueError:
raise MessageError("JSON decode failed on '%s ...'" % raw[6][:36])
elif mimetype == 'text/ascii':
msg['data'] = str(data)
msg['binary'] = False
elif mimetype == 'binary/octet-stream':
msg['data'] = data
msg['binary'] = True
else:
raise MessageError("Unknown mime-type '%s'" % mimetype)
return msg | python | def _decode(rawstr):
"""Convert a raw string to a Message.
"""
# Check for the magick word.
try:
rawstr = rawstr.decode('utf-8')
except (AttributeError, UnicodeEncodeError):
pass
except (UnicodeDecodeError):
try:
rawstr = rawstr.decode('iso-8859-1')
except (UnicodeDecodeError):
rawstr = rawstr.decode('utf-8', 'ignore')
if not rawstr.startswith(_MAGICK):
raise MessageError("This is not a '%s' message (wrong magick word)"
% _MAGICK)
rawstr = rawstr[len(_MAGICK):]
# Check for element count and version
raw = re.split(r"\s+", rawstr, maxsplit=6)
if len(raw) < 5:
raise MessageError("Could node decode raw string: '%s ...'"
% str(rawstr[:36]))
version = raw[4][:len(_VERSION)]
if not _is_valid_version(version):
raise MessageError("Invalid Message version: '%s'" % str(version))
# Start to build message
msg = dict((('subject', raw[0].strip()),
('type', raw[1].strip()),
('sender', raw[2].strip()),
('time', strp_isoformat(raw[3].strip())),
('version', version)))
# Data part
try:
mimetype = raw[5].lower()
data = raw[6]
except IndexError:
mimetype = None
if mimetype is None:
msg['data'] = ''
msg['binary'] = False
elif mimetype == 'application/json':
try:
msg['data'] = json.loads(raw[6], object_hook=datetime_decoder)
msg['binary'] = False
except ValueError:
raise MessageError("JSON decode failed on '%s ...'" % raw[6][:36])
elif mimetype == 'text/ascii':
msg['data'] = str(data)
msg['binary'] = False
elif mimetype == 'binary/octet-stream':
msg['data'] = data
msg['binary'] = True
else:
raise MessageError("Unknown mime-type '%s'" % mimetype)
return msg | [
"def",
"_decode",
"(",
"rawstr",
")",
":",
"# Check for the magick word.",
"try",
":",
"rawstr",
"=",
"rawstr",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"(",
"AttributeError",
",",
"UnicodeEncodeError",
")",
":",
"pass",
"except",
"(",
"UnicodeDecodeError",... | Convert a raw string to a Message. | [
"Convert",
"a",
"raw",
"string",
"to",
"a",
"Message",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L247-L306 | train | 49,774 |
pytroll/posttroll | posttroll/message.py | _encode | def _encode(msg, head=False, binary=False):
"""Convert a Message to a raw string.
"""
rawstr = str(_MAGICK) + u"{0:s} {1:s} {2:s} {3:s} {4:s}".format(
msg.subject, msg.type, msg.sender, msg.time.isoformat(), msg.version)
if not head and msg.data:
if not binary and isinstance(msg.data, six.string_types):
return (rawstr + ' ' +
'text/ascii' + ' ' + msg.data)
elif not binary:
return (rawstr + ' ' +
'application/json' + ' ' +
json.dumps(msg.data, default=datetime_encoder))
else:
return (rawstr + ' ' +
'binary/octet-stream' + ' ' + msg.data)
return rawstr | python | def _encode(msg, head=False, binary=False):
"""Convert a Message to a raw string.
"""
rawstr = str(_MAGICK) + u"{0:s} {1:s} {2:s} {3:s} {4:s}".format(
msg.subject, msg.type, msg.sender, msg.time.isoformat(), msg.version)
if not head and msg.data:
if not binary and isinstance(msg.data, six.string_types):
return (rawstr + ' ' +
'text/ascii' + ' ' + msg.data)
elif not binary:
return (rawstr + ' ' +
'application/json' + ' ' +
json.dumps(msg.data, default=datetime_encoder))
else:
return (rawstr + ' ' +
'binary/octet-stream' + ' ' + msg.data)
return rawstr | [
"def",
"_encode",
"(",
"msg",
",",
"head",
"=",
"False",
",",
"binary",
"=",
"False",
")",
":",
"rawstr",
"=",
"str",
"(",
"_MAGICK",
")",
"+",
"u\"{0:s} {1:s} {2:s} {3:s} {4:s}\"",
".",
"format",
"(",
"msg",
".",
"subject",
",",
"msg",
".",
"type",
",... | Convert a Message to a raw string. | [
"Convert",
"a",
"Message",
"to",
"a",
"raw",
"string",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L318-L335 | train | 49,775 |
pytroll/posttroll | posttroll/message.py | _getsender | def _getsender():
"""Return local sender.
Don't use the getpass module, it looks at various environment variables
and is unreliable.
"""
import os
import pwd
import socket
host = socket.gethostname()
user = pwd.getpwuid(os.getuid())[0]
return "%s@%s" % (user, host) | python | def _getsender():
"""Return local sender.
Don't use the getpass module, it looks at various environment variables
and is unreliable.
"""
import os
import pwd
import socket
host = socket.gethostname()
user = pwd.getpwuid(os.getuid())[0]
return "%s@%s" % (user, host) | [
"def",
"_getsender",
"(",
")",
":",
"import",
"os",
"import",
"pwd",
"import",
"socket",
"host",
"=",
"socket",
".",
"gethostname",
"(",
")",
"user",
"=",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"getuid",
"(",
")",
")",
"[",
"0",
"]",
"return",
"\"... | Return local sender.
Don't use the getpass module, it looks at various environment variables
and is unreliable. | [
"Return",
"local",
"sender",
".",
"Don",
"t",
"use",
"the",
"getpass",
"module",
"it",
"looks",
"at",
"various",
"environment",
"variables",
"and",
"is",
"unreliable",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L344-L354 | train | 49,776 |
pytroll/posttroll | posttroll/message.py | Message._validate | def _validate(self):
"""Validate a messages attributes.
"""
if not is_valid_subject(self.subject):
raise MessageError("Invalid subject: '%s'" % self.subject)
if not is_valid_type(self.type):
raise MessageError("Invalid type: '%s'" % self.type)
if not is_valid_sender(self.sender):
raise MessageError("Invalid sender: '%s'" % self.sender)
if not self.binary and not is_valid_data(self.data):
raise MessageError("Invalid data: data is not JSON serializable: %s"
% str(self.data)) | python | def _validate(self):
"""Validate a messages attributes.
"""
if not is_valid_subject(self.subject):
raise MessageError("Invalid subject: '%s'" % self.subject)
if not is_valid_type(self.type):
raise MessageError("Invalid type: '%s'" % self.type)
if not is_valid_sender(self.sender):
raise MessageError("Invalid sender: '%s'" % self.sender)
if not self.binary and not is_valid_data(self.data):
raise MessageError("Invalid data: data is not JSON serializable: %s"
% str(self.data)) | [
"def",
"_validate",
"(",
"self",
")",
":",
"if",
"not",
"is_valid_subject",
"(",
"self",
".",
"subject",
")",
":",
"raise",
"MessageError",
"(",
"\"Invalid subject: '%s'\"",
"%",
"self",
".",
"subject",
")",
"if",
"not",
"is_valid_type",
"(",
"self",
".",
... | Validate a messages attributes. | [
"Validate",
"a",
"messages",
"attributes",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L188-L199 | train | 49,777 |
Syndace/python-x3dh | x3dh/state.py | State.__generateSPK | def __generateSPK(self):
"""
Generate a new PK and sign its public key using the IK, add the timestamp aswell
to allow for periodic rotations.
"""
key = self.__KeyPair.generate()
key_serialized = self.__PublicKeyEncoder.encodePublicKey(
key.pub,
self.__curve
)
signature = self.__XEdDSA(mont_priv = self.__ik.priv).sign(key_serialized)
self.__spk = {
"key": key,
"signature": signature,
"timestamp": time.time()
} | python | def __generateSPK(self):
"""
Generate a new PK and sign its public key using the IK, add the timestamp aswell
to allow for periodic rotations.
"""
key = self.__KeyPair.generate()
key_serialized = self.__PublicKeyEncoder.encodePublicKey(
key.pub,
self.__curve
)
signature = self.__XEdDSA(mont_priv = self.__ik.priv).sign(key_serialized)
self.__spk = {
"key": key,
"signature": signature,
"timestamp": time.time()
} | [
"def",
"__generateSPK",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"__KeyPair",
".",
"generate",
"(",
")",
"key_serialized",
"=",
"self",
".",
"__PublicKeyEncoder",
".",
"encodePublicKey",
"(",
"key",
".",
"pub",
",",
"self",
".",
"__curve",
")",
"s... | Generate a new PK and sign its public key using the IK, add the timestamp aswell
to allow for periodic rotations. | [
"Generate",
"a",
"new",
"PK",
"and",
"sign",
"its",
"public",
"key",
"using",
"the",
"IK",
"add",
"the",
"timestamp",
"aswell",
"to",
"allow",
"for",
"periodic",
"rotations",
"."
] | a6cec1ae858121b88bef1b178f5cda5e43d5c391 | https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L152-L171 | train | 49,778 |
Syndace/python-x3dh | x3dh/state.py | State.__generateOTPKs | def __generateOTPKs(self, num_otpks = None):
"""
Generate the given amount of OTPKs.
:param num_otpks: Either an integer or None.
If the value of num_otpks is None, set it to the max_num_otpks value of the
configuration.
"""
if num_otpks == None:
num_otpks = self.__max_num_otpks
otpks = []
for _ in range(num_otpks):
otpks.append(self.__KeyPair.generate())
try:
self.__otpks.extend(otpks)
except AttributeError:
self.__otpks = otpks | python | def __generateOTPKs(self, num_otpks = None):
"""
Generate the given amount of OTPKs.
:param num_otpks: Either an integer or None.
If the value of num_otpks is None, set it to the max_num_otpks value of the
configuration.
"""
if num_otpks == None:
num_otpks = self.__max_num_otpks
otpks = []
for _ in range(num_otpks):
otpks.append(self.__KeyPair.generate())
try:
self.__otpks.extend(otpks)
except AttributeError:
self.__otpks = otpks | [
"def",
"__generateOTPKs",
"(",
"self",
",",
"num_otpks",
"=",
"None",
")",
":",
"if",
"num_otpks",
"==",
"None",
":",
"num_otpks",
"=",
"self",
".",
"__max_num_otpks",
"otpks",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"num_otpks",
")",
":",
"otpk... | Generate the given amount of OTPKs.
:param num_otpks: Either an integer or None.
If the value of num_otpks is None, set it to the max_num_otpks value of the
configuration. | [
"Generate",
"the",
"given",
"amount",
"of",
"OTPKs",
"."
] | a6cec1ae858121b88bef1b178f5cda5e43d5c391 | https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L174-L195 | train | 49,779 |
Syndace/python-x3dh | x3dh/state.py | State.__checkSPKTimestamp | def __checkSPKTimestamp(self):
"""
Check whether the SPK is too old and generate a new one in that case.
"""
if time.time() - self.__spk["timestamp"] > self.__spk_timeout:
self.__generateSPK() | python | def __checkSPKTimestamp(self):
"""
Check whether the SPK is too old and generate a new one in that case.
"""
if time.time() - self.__spk["timestamp"] > self.__spk_timeout:
self.__generateSPK() | [
"def",
"__checkSPKTimestamp",
"(",
"self",
")",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"__spk",
"[",
"\"timestamp\"",
"]",
">",
"self",
".",
"__spk_timeout",
":",
"self",
".",
"__generateSPK",
"(",
")"
] | Check whether the SPK is too old and generate a new one in that case. | [
"Check",
"whether",
"the",
"SPK",
"is",
"too",
"old",
"and",
"generate",
"a",
"new",
"one",
"in",
"that",
"case",
"."
] | a6cec1ae858121b88bef1b178f5cda5e43d5c391 | https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L230-L236 | train | 49,780 |
Syndace/python-x3dh | x3dh/state.py | State.__refillOTPKs | def __refillOTPKs(self):
"""
If the amount of available OTPKs fell under the minimum, refills the OTPKs up to
the maximum limit again.
"""
remainingOTPKs = len(self.__otpks)
if remainingOTPKs < self.__min_num_otpks:
self.__generateOTPKs(self.__max_num_otpks - remainingOTPKs) | python | def __refillOTPKs(self):
"""
If the amount of available OTPKs fell under the minimum, refills the OTPKs up to
the maximum limit again.
"""
remainingOTPKs = len(self.__otpks)
if remainingOTPKs < self.__min_num_otpks:
self.__generateOTPKs(self.__max_num_otpks - remainingOTPKs) | [
"def",
"__refillOTPKs",
"(",
"self",
")",
":",
"remainingOTPKs",
"=",
"len",
"(",
"self",
".",
"__otpks",
")",
"if",
"remainingOTPKs",
"<",
"self",
".",
"__min_num_otpks",
":",
"self",
".",
"__generateOTPKs",
"(",
"self",
".",
"__max_num_otpks",
"-",
"remain... | If the amount of available OTPKs fell under the minimum, refills the OTPKs up to
the maximum limit again. | [
"If",
"the",
"amount",
"of",
"available",
"OTPKs",
"fell",
"under",
"the",
"minimum",
"refills",
"the",
"OTPKs",
"up",
"to",
"the",
"maximum",
"limit",
"again",
"."
] | a6cec1ae858121b88bef1b178f5cda5e43d5c391 | https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L238-L247 | train | 49,781 |
Syndace/python-x3dh | x3dh/state.py | State.hideFromPublicBundle | def hideFromPublicBundle(self, otpk_pub):
"""
Hide a one-time pre key from the public bundle.
:param otpk_pub: The public key of the one-time pre key to hide, encoded as a
bytes-like object.
"""
self.__checkSPKTimestamp()
for otpk in self.__otpks:
if otpk.pub == otpk_pub:
self.__otpks.remove(otpk)
self.__hidden_otpks.append(otpk)
self.__refillOTPKs() | python | def hideFromPublicBundle(self, otpk_pub):
"""
Hide a one-time pre key from the public bundle.
:param otpk_pub: The public key of the one-time pre key to hide, encoded as a
bytes-like object.
"""
self.__checkSPKTimestamp()
for otpk in self.__otpks:
if otpk.pub == otpk_pub:
self.__otpks.remove(otpk)
self.__hidden_otpks.append(otpk)
self.__refillOTPKs() | [
"def",
"hideFromPublicBundle",
"(",
"self",
",",
"otpk_pub",
")",
":",
"self",
".",
"__checkSPKTimestamp",
"(",
")",
"for",
"otpk",
"in",
"self",
".",
"__otpks",
":",
"if",
"otpk",
".",
"pub",
"==",
"otpk_pub",
":",
"self",
".",
"__otpks",
".",
"remove",... | Hide a one-time pre key from the public bundle.
:param otpk_pub: The public key of the one-time pre key to hide, encoded as a
bytes-like object. | [
"Hide",
"a",
"one",
"-",
"time",
"pre",
"key",
"from",
"the",
"public",
"bundle",
"."
] | a6cec1ae858121b88bef1b178f5cda5e43d5c391 | https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L250-L264 | train | 49,782 |
Syndace/python-x3dh | x3dh/state.py | State.deleteOTPK | def deleteOTPK(self, otpk_pub):
"""
Delete a one-time pre key, either publicly visible or hidden.
:param otpk_pub: The public key of the one-time pre key to delete, encoded as a
bytes-like object.
"""
self.__checkSPKTimestamp()
for otpk in self.__otpks:
if otpk.pub == otpk_pub:
self.__otpks.remove(otpk)
for otpk in self.__hidden_otpks:
if otpk.pub == otpk_pub:
self.__hidden_otpks.remove(otpk)
self.__refillOTPKs() | python | def deleteOTPK(self, otpk_pub):
"""
Delete a one-time pre key, either publicly visible or hidden.
:param otpk_pub: The public key of the one-time pre key to delete, encoded as a
bytes-like object.
"""
self.__checkSPKTimestamp()
for otpk in self.__otpks:
if otpk.pub == otpk_pub:
self.__otpks.remove(otpk)
for otpk in self.__hidden_otpks:
if otpk.pub == otpk_pub:
self.__hidden_otpks.remove(otpk)
self.__refillOTPKs() | [
"def",
"deleteOTPK",
"(",
"self",
",",
"otpk_pub",
")",
":",
"self",
".",
"__checkSPKTimestamp",
"(",
")",
"for",
"otpk",
"in",
"self",
".",
"__otpks",
":",
"if",
"otpk",
".",
"pub",
"==",
"otpk_pub",
":",
"self",
".",
"__otpks",
".",
"remove",
"(",
... | Delete a one-time pre key, either publicly visible or hidden.
:param otpk_pub: The public key of the one-time pre key to delete, encoded as a
bytes-like object. | [
"Delete",
"a",
"one",
"-",
"time",
"pre",
"key",
"either",
"publicly",
"visible",
"or",
"hidden",
"."
] | a6cec1ae858121b88bef1b178f5cda5e43d5c391 | https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L267-L285 | train | 49,783 |
Syndace/python-x3dh | x3dh/state.py | State.getPublicBundle | def getPublicBundle(self):
"""
Fill a PublicBundle object with the public bundle data of this State.
:returns: An instance of PublicBundle, filled with the public data of this State.
"""
self.__checkSPKTimestamp()
ik_pub = self.__ik.pub
spk_pub = self.__spk["key"].pub
spk_sig = self.__spk["signature"]
otpk_pubs = [ otpk.pub for otpk in self.__otpks ]
return PublicBundle(ik_pub, spk_pub, spk_sig, otpk_pubs) | python | def getPublicBundle(self):
"""
Fill a PublicBundle object with the public bundle data of this State.
:returns: An instance of PublicBundle, filled with the public data of this State.
"""
self.__checkSPKTimestamp()
ik_pub = self.__ik.pub
spk_pub = self.__spk["key"].pub
spk_sig = self.__spk["signature"]
otpk_pubs = [ otpk.pub for otpk in self.__otpks ]
return PublicBundle(ik_pub, spk_pub, spk_sig, otpk_pubs) | [
"def",
"getPublicBundle",
"(",
"self",
")",
":",
"self",
".",
"__checkSPKTimestamp",
"(",
")",
"ik_pub",
"=",
"self",
".",
"__ik",
".",
"pub",
"spk_pub",
"=",
"self",
".",
"__spk",
"[",
"\"key\"",
"]",
".",
"pub",
"spk_sig",
"=",
"self",
".",
"__spk",
... | Fill a PublicBundle object with the public bundle data of this State.
:returns: An instance of PublicBundle, filled with the public data of this State. | [
"Fill",
"a",
"PublicBundle",
"object",
"with",
"the",
"public",
"bundle",
"data",
"of",
"this",
"State",
"."
] | a6cec1ae858121b88bef1b178f5cda5e43d5c391 | https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L291-L305 | train | 49,784 |
Syndace/python-x3dh | x3dh/state.py | State.getSharedSecretActive | def getSharedSecretActive(
self,
other_public_bundle,
allow_zero_otpks = False
):
"""
Do the key exchange, as the active party. This involves selecting keys from the
passive parties' public bundle.
:param other_public_bundle: An instance of PublicBundle, filled with the public
data of the passive party.
:param allow_zero_otpks: A flag indicating whether bundles with no one-time pre
keys are allowed or throw an error. False is the recommended default.
:returns: A dictionary containing the shared secret, the shared associated data
and the data the passive party needs to finalize the key exchange.
The returned structure looks like this::
{
"to_other": {
# The public key of the active parties' identity key pair
"ik": bytes,
# The public key of the active parties' ephemeral key pair
"ek": bytes,
# The public key of the used passive parties' one-time pre key or None
"otpk": bytes or None,
# The public key of the passive parties' signed pre key pair
"spk": bytes
},
"ad": bytes, # The shared associated data
"sk": bytes # The shared secret
}
:raises KeyExchangeException: If an error occurs during the key exchange. The
exception message will contain (human-readable) details.
"""
self.__checkSPKTimestamp()
other_ik = self.__KeyPair(pub = other_public_bundle.ik)
other_spk = {
"key": self.__KeyPair(pub = other_public_bundle.spk),
"signature": other_public_bundle.spk_signature
}
other_otpks = [
self.__KeyPair(pub = otpk) for otpk in other_public_bundle.otpks
]
if len(other_otpks) == 0 and not allow_zero_otpks:
raise KeyExchangeException(
"The other public bundle does not contain any OTPKs, which is not " +
"allowed."
)
other_spk_serialized = self.__PublicKeyEncoder.encodePublicKey(
other_spk["key"].pub,
self.__curve
)
if not self.__XEdDSA(mont_pub = other_ik.pub).verify(
other_spk_serialized,
other_spk["signature"]
):
raise KeyExchangeException(
"The signature of this public bundle's spk could not be verifified."
)
ek = self.__KeyPair.generate()
dh1 = self.__ik.getSharedSecret(other_spk["key"])
dh2 = ek.getSharedSecret(other_ik)
dh3 = ek.getSharedSecret(other_spk["key"])
dh4 = b""
otpk = None
if len(other_otpks) > 0:
otpk_index = ord(os.urandom(1)) % len(other_otpks)
otpk = other_otpks[otpk_index]
dh4 = ek.getSharedSecret(otpk)
sk = self.__kdf(dh1 + dh2 + dh3 + dh4)
ik_pub_serialized = self.__PublicKeyEncoder.encodePublicKey(
self.__ik.pub,
self.__curve
)
other_ik_pub_serialized = self.__PublicKeyEncoder.encodePublicKey(
other_ik.pub,
self.__curve
)
ad = ik_pub_serialized + other_ik_pub_serialized
return {
"to_other": {
"ik": self.__ik.pub,
"ek": ek.pub,
"otpk": otpk.pub if otpk else None,
"spk": other_spk["key"].pub
},
"ad": ad,
"sk": sk
} | python | def getSharedSecretActive(
self,
other_public_bundle,
allow_zero_otpks = False
):
"""
Do the key exchange, as the active party. This involves selecting keys from the
passive parties' public bundle.
:param other_public_bundle: An instance of PublicBundle, filled with the public
data of the passive party.
:param allow_zero_otpks: A flag indicating whether bundles with no one-time pre
keys are allowed or throw an error. False is the recommended default.
:returns: A dictionary containing the shared secret, the shared associated data
and the data the passive party needs to finalize the key exchange.
The returned structure looks like this::
{
"to_other": {
# The public key of the active parties' identity key pair
"ik": bytes,
# The public key of the active parties' ephemeral key pair
"ek": bytes,
# The public key of the used passive parties' one-time pre key or None
"otpk": bytes or None,
# The public key of the passive parties' signed pre key pair
"spk": bytes
},
"ad": bytes, # The shared associated data
"sk": bytes # The shared secret
}
:raises KeyExchangeException: If an error occurs during the key exchange. The
exception message will contain (human-readable) details.
"""
self.__checkSPKTimestamp()
other_ik = self.__KeyPair(pub = other_public_bundle.ik)
other_spk = {
"key": self.__KeyPair(pub = other_public_bundle.spk),
"signature": other_public_bundle.spk_signature
}
other_otpks = [
self.__KeyPair(pub = otpk) for otpk in other_public_bundle.otpks
]
if len(other_otpks) == 0 and not allow_zero_otpks:
raise KeyExchangeException(
"The other public bundle does not contain any OTPKs, which is not " +
"allowed."
)
other_spk_serialized = self.__PublicKeyEncoder.encodePublicKey(
other_spk["key"].pub,
self.__curve
)
if not self.__XEdDSA(mont_pub = other_ik.pub).verify(
other_spk_serialized,
other_spk["signature"]
):
raise KeyExchangeException(
"The signature of this public bundle's spk could not be verifified."
)
ek = self.__KeyPair.generate()
dh1 = self.__ik.getSharedSecret(other_spk["key"])
dh2 = ek.getSharedSecret(other_ik)
dh3 = ek.getSharedSecret(other_spk["key"])
dh4 = b""
otpk = None
if len(other_otpks) > 0:
otpk_index = ord(os.urandom(1)) % len(other_otpks)
otpk = other_otpks[otpk_index]
dh4 = ek.getSharedSecret(otpk)
sk = self.__kdf(dh1 + dh2 + dh3 + dh4)
ik_pub_serialized = self.__PublicKeyEncoder.encodePublicKey(
self.__ik.pub,
self.__curve
)
other_ik_pub_serialized = self.__PublicKeyEncoder.encodePublicKey(
other_ik.pub,
self.__curve
)
ad = ik_pub_serialized + other_ik_pub_serialized
return {
"to_other": {
"ik": self.__ik.pub,
"ek": ek.pub,
"otpk": otpk.pub if otpk else None,
"spk": other_spk["key"].pub
},
"ad": ad,
"sk": sk
} | [
"def",
"getSharedSecretActive",
"(",
"self",
",",
"other_public_bundle",
",",
"allow_zero_otpks",
"=",
"False",
")",
":",
"self",
".",
"__checkSPKTimestamp",
"(",
")",
"other_ik",
"=",
"self",
".",
"__KeyPair",
"(",
"pub",
"=",
"other_public_bundle",
".",
"ik",
... | Do the key exchange, as the active party. This involves selecting keys from the
passive parties' public bundle.
:param other_public_bundle: An instance of PublicBundle, filled with the public
data of the passive party.
:param allow_zero_otpks: A flag indicating whether bundles with no one-time pre
keys are allowed or throw an error. False is the recommended default.
:returns: A dictionary containing the shared secret, the shared associated data
and the data the passive party needs to finalize the key exchange.
The returned structure looks like this::
{
"to_other": {
# The public key of the active parties' identity key pair
"ik": bytes,
# The public key of the active parties' ephemeral key pair
"ek": bytes,
# The public key of the used passive parties' one-time pre key or None
"otpk": bytes or None,
# The public key of the passive parties' signed pre key pair
"spk": bytes
},
"ad": bytes, # The shared associated data
"sk": bytes # The shared secret
}
:raises KeyExchangeException: If an error occurs during the key exchange. The
exception message will contain (human-readable) details. | [
"Do",
"the",
"key",
"exchange",
"as",
"the",
"active",
"party",
".",
"This",
"involves",
"selecting",
"keys",
"from",
"the",
"passive",
"parties",
"public",
"bundle",
"."
] | a6cec1ae858121b88bef1b178f5cda5e43d5c391 | https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L329-L438 | train | 49,785 |
Syndace/python-x3dh | x3dh/state.py | State.getSharedSecretPassive | def getSharedSecretPassive(
self,
passive_exchange_data,
allow_no_otpk = False,
keep_otpk = False
):
"""
Do the key exchange, as the passive party. This involves retrieving data about the
key exchange from the active party.
:param passive_exchange_data: A structure generated by the active party, which
contains data requried to complete the key exchange. See the "to_other" part
of the structure returned by "getSharedSecretActive".
:param allow_no_otpk: A boolean indicating whether to allow key exchange, even if
the active party did not use a one-time pre key. The recommended default is
False.
:param keep_otpk: Keep the one-time pre key after using it, instead of deleting
it. See the notes below.
:returns: A dictionary containing the shared secret and the shared associated
data.
The returned structure looks like this::
{
"ad": bytes, # The shared associated data
"sk": bytes # The shared secret
}
The specification of X3DH dictates to delete one-time pre keys as soon as they are
used.
This behaviour provides security but may lead to considerable usability downsides
in some environments.
For that reason the keep_otpk flag exists.
If set to True, the one-time pre key is not automatically deleted.
USE WITH CARE, THIS MAY INTRODUCE SECURITY LEAKS IF USED INCORRECTLY.
If you decide to set the flag and to keep the otpks, you have to manage deleting
them yourself, e.g. by subclassing this class and overriding this method.
:raises KeyExchangeException: If an error occurs during the key exchange. The
exception message will contain (human-readable) details.
"""
self.__checkSPKTimestamp()
other_ik = self.__KeyPair(pub = passive_exchange_data["ik"])
other_ek = self.__KeyPair(pub = passive_exchange_data["ek"])
if self.__spk["key"].pub != passive_exchange_data["spk"]:
raise KeyExchangeException(
"The SPK used for this key exchange has been rotated, the key exchange " +
"can not be completed."
)
my_otpk = None
if "otpk" in passive_exchange_data:
for otpk in self.__otpks:
if otpk.pub == passive_exchange_data["otpk"]:
my_otpk = otpk
break
for otpk in self.__hidden_otpks:
if otpk.pub == passive_exchange_data["otpk"]:
my_otpk = otpk
break
if not my_otpk:
raise KeyExchangeException(
"The OTPK used for this key exchange has been deleted, the key " +
"exchange can not be completed."
)
elif not allow_no_otpk:
raise KeyExchangeException(
"This key exchange data does not contain an OTPK, which is not allowed."
)
dh1 = self.__spk["key"].getSharedSecret(other_ik)
dh2 = self.__ik.getSharedSecret(other_ek)
dh3 = self.__spk["key"].getSharedSecret(other_ek)
dh4 = b""
if my_otpk:
dh4 = my_otpk.getSharedSecret(other_ek)
sk = self.__kdf(dh1 + dh2 + dh3 + dh4)
other_ik_pub_serialized = self.__PublicKeyEncoder.encodePublicKey(
other_ik.pub,
self.__curve
)
ik_pub_serialized = self.__PublicKeyEncoder.encodePublicKey(
self.__ik.pub,
self.__curve
)
ad = other_ik_pub_serialized + ik_pub_serialized
if my_otpk and not keep_otpk:
self.deleteOTPK(my_otpk.pub)
return {
"ad": ad,
"sk": sk
} | python | def getSharedSecretPassive(
self,
passive_exchange_data,
allow_no_otpk = False,
keep_otpk = False
):
"""
Do the key exchange, as the passive party. This involves retrieving data about the
key exchange from the active party.
:param passive_exchange_data: A structure generated by the active party, which
contains data requried to complete the key exchange. See the "to_other" part
of the structure returned by "getSharedSecretActive".
:param allow_no_otpk: A boolean indicating whether to allow key exchange, even if
the active party did not use a one-time pre key. The recommended default is
False.
:param keep_otpk: Keep the one-time pre key after using it, instead of deleting
it. See the notes below.
:returns: A dictionary containing the shared secret and the shared associated
data.
The returned structure looks like this::
{
"ad": bytes, # The shared associated data
"sk": bytes # The shared secret
}
The specification of X3DH dictates to delete one-time pre keys as soon as they are
used.
This behaviour provides security but may lead to considerable usability downsides
in some environments.
For that reason the keep_otpk flag exists.
If set to True, the one-time pre key is not automatically deleted.
USE WITH CARE, THIS MAY INTRODUCE SECURITY LEAKS IF USED INCORRECTLY.
If you decide to set the flag and to keep the otpks, you have to manage deleting
them yourself, e.g. by subclassing this class and overriding this method.
:raises KeyExchangeException: If an error occurs during the key exchange. The
exception message will contain (human-readable) details.
"""
self.__checkSPKTimestamp()
other_ik = self.__KeyPair(pub = passive_exchange_data["ik"])
other_ek = self.__KeyPair(pub = passive_exchange_data["ek"])
if self.__spk["key"].pub != passive_exchange_data["spk"]:
raise KeyExchangeException(
"The SPK used for this key exchange has been rotated, the key exchange " +
"can not be completed."
)
my_otpk = None
if "otpk" in passive_exchange_data:
for otpk in self.__otpks:
if otpk.pub == passive_exchange_data["otpk"]:
my_otpk = otpk
break
for otpk in self.__hidden_otpks:
if otpk.pub == passive_exchange_data["otpk"]:
my_otpk = otpk
break
if not my_otpk:
raise KeyExchangeException(
"The OTPK used for this key exchange has been deleted, the key " +
"exchange can not be completed."
)
elif not allow_no_otpk:
raise KeyExchangeException(
"This key exchange data does not contain an OTPK, which is not allowed."
)
dh1 = self.__spk["key"].getSharedSecret(other_ik)
dh2 = self.__ik.getSharedSecret(other_ek)
dh3 = self.__spk["key"].getSharedSecret(other_ek)
dh4 = b""
if my_otpk:
dh4 = my_otpk.getSharedSecret(other_ek)
sk = self.__kdf(dh1 + dh2 + dh3 + dh4)
other_ik_pub_serialized = self.__PublicKeyEncoder.encodePublicKey(
other_ik.pub,
self.__curve
)
ik_pub_serialized = self.__PublicKeyEncoder.encodePublicKey(
self.__ik.pub,
self.__curve
)
ad = other_ik_pub_serialized + ik_pub_serialized
if my_otpk and not keep_otpk:
self.deleteOTPK(my_otpk.pub)
return {
"ad": ad,
"sk": sk
} | [
"def",
"getSharedSecretPassive",
"(",
"self",
",",
"passive_exchange_data",
",",
"allow_no_otpk",
"=",
"False",
",",
"keep_otpk",
"=",
"False",
")",
":",
"self",
".",
"__checkSPKTimestamp",
"(",
")",
"other_ik",
"=",
"self",
".",
"__KeyPair",
"(",
"pub",
"=",
... | Do the key exchange, as the passive party. This involves retrieving data about the
key exchange from the active party.
:param passive_exchange_data: A structure generated by the active party, which
contains data requried to complete the key exchange. See the "to_other" part
of the structure returned by "getSharedSecretActive".
:param allow_no_otpk: A boolean indicating whether to allow key exchange, even if
the active party did not use a one-time pre key. The recommended default is
False.
:param keep_otpk: Keep the one-time pre key after using it, instead of deleting
it. See the notes below.
:returns: A dictionary containing the shared secret and the shared associated
data.
The returned structure looks like this::
{
"ad": bytes, # The shared associated data
"sk": bytes # The shared secret
}
The specification of X3DH dictates to delete one-time pre keys as soon as they are
used.
This behaviour provides security but may lead to considerable usability downsides
in some environments.
For that reason the keep_otpk flag exists.
If set to True, the one-time pre key is not automatically deleted.
USE WITH CARE, THIS MAY INTRODUCE SECURITY LEAKS IF USED INCORRECTLY.
If you decide to set the flag and to keep the otpks, you have to manage deleting
them yourself, e.g. by subclassing this class and overriding this method.
:raises KeyExchangeException: If an error occurs during the key exchange. The
exception message will contain (human-readable) details. | [
"Do",
"the",
"key",
"exchange",
"as",
"the",
"passive",
"party",
".",
"This",
"involves",
"retrieving",
"data",
"about",
"the",
"key",
"exchange",
"from",
"the",
"active",
"party",
"."
] | a6cec1ae858121b88bef1b178f5cda5e43d5c391 | https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L440-L545 | train | 49,786 |
kislyuk/tweak | tweak/__init__.py | Config.save | def save(self, mode=0o600):
"""
Serialize the config data to the user home directory.
:param mode: The octal Unix mode (permissions) for the config file.
"""
if self._parent is not None:
self._parent.save(mode=mode)
else:
config_dir = os.path.dirname(os.path.abspath(self.config_files[-1]))
try:
os.makedirs(config_dir)
except OSError as e:
if not (e.errno == errno.EEXIST and os.path.isdir(config_dir)):
raise
with open(self.config_files[-1], "wb" if sys.version_info < (3, 0) else "w") as fh:
self._dump(fh)
os.chmod(self.config_files[-1], mode)
self._logger.debug("Saved config to %s", self.config_files[-1]) | python | def save(self, mode=0o600):
"""
Serialize the config data to the user home directory.
:param mode: The octal Unix mode (permissions) for the config file.
"""
if self._parent is not None:
self._parent.save(mode=mode)
else:
config_dir = os.path.dirname(os.path.abspath(self.config_files[-1]))
try:
os.makedirs(config_dir)
except OSError as e:
if not (e.errno == errno.EEXIST and os.path.isdir(config_dir)):
raise
with open(self.config_files[-1], "wb" if sys.version_info < (3, 0) else "w") as fh:
self._dump(fh)
os.chmod(self.config_files[-1], mode)
self._logger.debug("Saved config to %s", self.config_files[-1]) | [
"def",
"save",
"(",
"self",
",",
"mode",
"=",
"0o600",
")",
":",
"if",
"self",
".",
"_parent",
"is",
"not",
"None",
":",
"self",
".",
"_parent",
".",
"save",
"(",
"mode",
"=",
"mode",
")",
"else",
":",
"config_dir",
"=",
"os",
".",
"path",
".",
... | Serialize the config data to the user home directory.
:param mode: The octal Unix mode (permissions) for the config file. | [
"Serialize",
"the",
"config",
"data",
"to",
"the",
"user",
"home",
"directory",
"."
] | 0fec5fa8a21e46713c565a996f41c8b7c6793166 | https://github.com/kislyuk/tweak/blob/0fec5fa8a21e46713c565a996f41c8b7c6793166/tweak/__init__.py#L148-L166 | train | 49,787 |
daskol/nls | nls/model.py | AbstractModel.getChemicalPotential | def getChemicalPotential(self, solution):
"""Call solver in order to calculate chemical potential.
"""
if isinstance(solution, Solution):
solution = solution.getSolution()
self.mu = self.solver.chemicalPotential(solution)
return self.mu | python | def getChemicalPotential(self, solution):
"""Call solver in order to calculate chemical potential.
"""
if isinstance(solution, Solution):
solution = solution.getSolution()
self.mu = self.solver.chemicalPotential(solution)
return self.mu | [
"def",
"getChemicalPotential",
"(",
"self",
",",
"solution",
")",
":",
"if",
"isinstance",
"(",
"solution",
",",
"Solution",
")",
":",
"solution",
"=",
"solution",
".",
"getSolution",
"(",
")",
"self",
".",
"mu",
"=",
"self",
".",
"solver",
".",
"chemica... | Call solver in order to calculate chemical potential. | [
"Call",
"solver",
"in",
"order",
"to",
"calculate",
"chemical",
"potential",
"."
] | 00bb4555e4f56e222dc6f54faf2e286567519626 | https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/model.py#L196-L203 | train | 49,788 |
daskol/nls | nls/model.py | Solution.getDampingIntegral | def getDampingIntegral(self):
"""Calculate integral of damping terms of hamiltonian using rectangular method.
"""
reservoir = self.getReservoir()
density = self.getDensity()
length = self.model.getSpatialStep()
if self.solution.ndim == 1:
nodes = self.model.getNumberOfNodes()
radius = linspace(0, nodes * self.model.getSpatialStep(), nodes)
integral = 2 * pi * sum((reservoir - 1.0) * density * radius * length)
elif self.solution.ndim == 2:
area = length ** 2
integral = sum(sum((reservoir - 1.0) * density * area))
return integral | python | def getDampingIntegral(self):
"""Calculate integral of damping terms of hamiltonian using rectangular method.
"""
reservoir = self.getReservoir()
density = self.getDensity()
length = self.model.getSpatialStep()
if self.solution.ndim == 1:
nodes = self.model.getNumberOfNodes()
radius = linspace(0, nodes * self.model.getSpatialStep(), nodes)
integral = 2 * pi * sum((reservoir - 1.0) * density * radius * length)
elif self.solution.ndim == 2:
area = length ** 2
integral = sum(sum((reservoir - 1.0) * density * area))
return integral | [
"def",
"getDampingIntegral",
"(",
"self",
")",
":",
"reservoir",
"=",
"self",
".",
"getReservoir",
"(",
")",
"density",
"=",
"self",
".",
"getDensity",
"(",
")",
"length",
"=",
"self",
".",
"model",
".",
"getSpatialStep",
"(",
")",
"if",
"self",
".",
"... | Calculate integral of damping terms of hamiltonian using rectangular method. | [
"Calculate",
"integral",
"of",
"damping",
"terms",
"of",
"hamiltonian",
"using",
"rectangular",
"method",
"."
] | 00bb4555e4f56e222dc6f54faf2e286567519626 | https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/model.py#L350-L365 | train | 49,789 |
fudge-py/fudge | fudge/util.py | fmt_val | def fmt_val(val, shorten=True):
"""Format a value for inclusion in an
informative text string.
"""
val = repr(val)
max = 50
if shorten:
if len(val) > max:
close = val[-1]
val = val[0:max-4] + "..."
if close in (">", "'", '"', ']', '}', ')'):
val = val + close
return val | python | def fmt_val(val, shorten=True):
"""Format a value for inclusion in an
informative text string.
"""
val = repr(val)
max = 50
if shorten:
if len(val) > max:
close = val[-1]
val = val[0:max-4] + "..."
if close in (">", "'", '"', ']', '}', ')'):
val = val + close
return val | [
"def",
"fmt_val",
"(",
"val",
",",
"shorten",
"=",
"True",
")",
":",
"val",
"=",
"repr",
"(",
"val",
")",
"max",
"=",
"50",
"if",
"shorten",
":",
"if",
"len",
"(",
"val",
")",
">",
"max",
":",
"close",
"=",
"val",
"[",
"-",
"1",
"]",
"val",
... | Format a value for inclusion in an
informative text string. | [
"Format",
"a",
"value",
"for",
"inclusion",
"in",
"an",
"informative",
"text",
"string",
"."
] | b283fbc1a41900f3f5845b10b8c2ef9136a67ebc | https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/util.py#L15-L27 | train | 49,790 |
fudge-py/fudge | fudge/util.py | fmt_dict_vals | def fmt_dict_vals(dict_vals, shorten=True):
"""Returns list of key=val pairs formatted
for inclusion in an informative text string.
"""
items = dict_vals.items()
if not items:
return [fmt_val(None, shorten=shorten)]
return ["%s=%s" % (k, fmt_val(v, shorten=shorten)) for k,v in items] | python | def fmt_dict_vals(dict_vals, shorten=True):
"""Returns list of key=val pairs formatted
for inclusion in an informative text string.
"""
items = dict_vals.items()
if not items:
return [fmt_val(None, shorten=shorten)]
return ["%s=%s" % (k, fmt_val(v, shorten=shorten)) for k,v in items] | [
"def",
"fmt_dict_vals",
"(",
"dict_vals",
",",
"shorten",
"=",
"True",
")",
":",
"items",
"=",
"dict_vals",
".",
"items",
"(",
")",
"if",
"not",
"items",
":",
"return",
"[",
"fmt_val",
"(",
"None",
",",
"shorten",
"=",
"shorten",
")",
"]",
"return",
... | Returns list of key=val pairs formatted
for inclusion in an informative text string. | [
"Returns",
"list",
"of",
"key",
"=",
"val",
"pairs",
"formatted",
"for",
"inclusion",
"in",
"an",
"informative",
"text",
"string",
"."
] | b283fbc1a41900f3f5845b10b8c2ef9136a67ebc | https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/util.py#L29-L36 | train | 49,791 |
Clinical-Genomics/trailblazer | trailblazer/mip/start.py | MipCli.build_command | def build_command(self, config, **kwargs):
"""Builds the command to execute MIP."""
command = ['perl', self.script, CLI_OPTIONS['config']['option'], config]
for key, value in kwargs.items():
# enable passing in flags as "False" - shouldn't add command
if value:
command.append(CLI_OPTIONS[key]['option'])
if value is True:
command.append(CLI_OPTIONS[key].get('default', '1'))
else:
command.append(value)
return command | python | def build_command(self, config, **kwargs):
"""Builds the command to execute MIP."""
command = ['perl', self.script, CLI_OPTIONS['config']['option'], config]
for key, value in kwargs.items():
# enable passing in flags as "False" - shouldn't add command
if value:
command.append(CLI_OPTIONS[key]['option'])
if value is True:
command.append(CLI_OPTIONS[key].get('default', '1'))
else:
command.append(value)
return command | [
"def",
"build_command",
"(",
"self",
",",
"config",
",",
"*",
"*",
"kwargs",
")",
":",
"command",
"=",
"[",
"'perl'",
",",
"self",
".",
"script",
",",
"CLI_OPTIONS",
"[",
"'config'",
"]",
"[",
"'option'",
"]",
",",
"config",
"]",
"for",
"key",
",",
... | Builds the command to execute MIP. | [
"Builds",
"the",
"command",
"to",
"execute",
"MIP",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/start.py#L48-L59 | train | 49,792 |
Clinical-Genomics/trailblazer | trailblazer/mip/start.py | MipCli.execute | def execute(self, command):
"""Start a new MIP run."""
process = subprocess.Popen(
command,
preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL)
)
return process | python | def execute(self, command):
"""Start a new MIP run."""
process = subprocess.Popen(
command,
preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL)
)
return process | [
"def",
"execute",
"(",
"self",
",",
"command",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"preexec_fn",
"=",
"lambda",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGPIPE",
",",
"signal",
".",
"SIG_DFL",
")",
")",... | Start a new MIP run. | [
"Start",
"a",
"new",
"MIP",
"run",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/start.py#L63-L69 | train | 49,793 |
thespacedoctor/sherlock | sherlock/commonutils/update_wiki_pages.py | update_wiki_pages.update | def update(self):
"""
Update wiki pages
See class docstring for usage
"""
self.log.debug('starting the ``update`` method')
if "sherlock wiki root" not in self.settings:
print "Sherlock wiki settings not found in settings file"
return
staticTableInfo = self._get_table_infos()
viewInfo = self._get_view_infos()
streamedTableInfo = self._get_stream_view_infos()
self._create_md_tables(
tableData=staticTableInfo,
viewData=viewInfo,
streamData=streamedTableInfo
)
self._write_wiki_pages()
self._update_github()
self.log.debug('completed the ``update`` method')
return | python | def update(self):
"""
Update wiki pages
See class docstring for usage
"""
self.log.debug('starting the ``update`` method')
if "sherlock wiki root" not in self.settings:
print "Sherlock wiki settings not found in settings file"
return
staticTableInfo = self._get_table_infos()
viewInfo = self._get_view_infos()
streamedTableInfo = self._get_stream_view_infos()
self._create_md_tables(
tableData=staticTableInfo,
viewData=viewInfo,
streamData=streamedTableInfo
)
self._write_wiki_pages()
self._update_github()
self.log.debug('completed the ``update`` method')
return | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``update`` method'",
")",
"if",
"\"sherlock wiki root\"",
"not",
"in",
"self",
".",
"settings",
":",
"print",
"\"Sherlock wiki settings not found in settings file\"",
"return... | Update wiki pages
See class docstring for usage | [
"Update",
"wiki",
"pages"
] | 2c80fb6fa31b04e7820e6928e3d437a21e692dd3 | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L91-L115 | train | 49,794 |
thespacedoctor/sherlock | sherlock/commonutils/update_wiki_pages.py | update_wiki_pages._get_table_infos | def _get_table_infos(
self,
trimmed=False):
"""query the sherlock-catalogues database table metadata
"""
self.log.debug('starting the ``_get_table_infos`` method')
sqlQuery = u"""
SELECT * FROM crossmatch_catalogues.tcs_helper_catalogue_tables_info where legacy_table = 0 and table_name not like "legacy%%" and table_name not like "%%stream" order by number_of_rows desc;
""" % locals()
tableInfo = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
if trimmed:
cleanTable = []
for r in tableInfo:
orow = collections.OrderedDict(sorted({}.items()))
for c in self.basicColumns:
if c in r:
orow[c] = r[c]
cleanTable.append(orow)
tableInfo = cleanTable
self.log.debug('completed the ``_get_table_infos`` method')
return tableInfo | python | def _get_table_infos(
self,
trimmed=False):
"""query the sherlock-catalogues database table metadata
"""
self.log.debug('starting the ``_get_table_infos`` method')
sqlQuery = u"""
SELECT * FROM crossmatch_catalogues.tcs_helper_catalogue_tables_info where legacy_table = 0 and table_name not like "legacy%%" and table_name not like "%%stream" order by number_of_rows desc;
""" % locals()
tableInfo = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
if trimmed:
cleanTable = []
for r in tableInfo:
orow = collections.OrderedDict(sorted({}.items()))
for c in self.basicColumns:
if c in r:
orow[c] = r[c]
cleanTable.append(orow)
tableInfo = cleanTable
self.log.debug('completed the ``_get_table_infos`` method')
return tableInfo | [
"def",
"_get_table_infos",
"(",
"self",
",",
"trimmed",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_get_table_infos`` method'",
")",
"sqlQuery",
"=",
"u\"\"\"\n SELECT * FROM crossmatch_catalogues.tcs_helper_catalogue_tables_inf... | query the sherlock-catalogues database table metadata | [
"query",
"the",
"sherlock",
"-",
"catalogues",
"database",
"table",
"metadata"
] | 2c80fb6fa31b04e7820e6928e3d437a21e692dd3 | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L117-L145 | train | 49,795 |
thespacedoctor/sherlock | sherlock/commonutils/update_wiki_pages.py | update_wiki_pages._get_view_infos | def _get_view_infos(
self,
trimmed=False):
"""query the sherlock-catalogues database view metadata
"""
self.log.debug('starting the ``_get_view_infos`` method')
sqlQuery = u"""
SELECT v.*, t.description as "master table" FROM crossmatch_catalogues.tcs_helper_catalogue_views_info as v, crossmatch_catalogues.tcs_helper_catalogue_tables_info AS t where v.legacy_view = 0 and v.view_name not like "legacy%%" and t.id=v.table_id order by number_of_rows desc
""" % locals()
viewInfo = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
if trimmed:
cleanTable = []
for r in viewInfo:
orow = collections.OrderedDict(sorted({}.items()))
for c in self.basicColumns:
if c in r:
orow[c] = r[c]
cleanTable.append(orow)
viewInfo = cleanTable
self.log.debug('completed the ``_get_view_infos`` method')
return viewInfo | python | def _get_view_infos(
self,
trimmed=False):
"""query the sherlock-catalogues database view metadata
"""
self.log.debug('starting the ``_get_view_infos`` method')
sqlQuery = u"""
SELECT v.*, t.description as "master table" FROM crossmatch_catalogues.tcs_helper_catalogue_views_info as v, crossmatch_catalogues.tcs_helper_catalogue_tables_info AS t where v.legacy_view = 0 and v.view_name not like "legacy%%" and t.id=v.table_id order by number_of_rows desc
""" % locals()
viewInfo = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
if trimmed:
cleanTable = []
for r in viewInfo:
orow = collections.OrderedDict(sorted({}.items()))
for c in self.basicColumns:
if c in r:
orow[c] = r[c]
cleanTable.append(orow)
viewInfo = cleanTable
self.log.debug('completed the ``_get_view_infos`` method')
return viewInfo | [
"def",
"_get_view_infos",
"(",
"self",
",",
"trimmed",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_get_view_infos`` method'",
")",
"sqlQuery",
"=",
"u\"\"\"\n SELECT v.*, t.description as \"master table\" FROM crossmatch_catalog... | query the sherlock-catalogues database view metadata | [
"query",
"the",
"sherlock",
"-",
"catalogues",
"database",
"view",
"metadata"
] | 2c80fb6fa31b04e7820e6928e3d437a21e692dd3 | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L147-L175 | train | 49,796 |
thespacedoctor/sherlock | sherlock/commonutils/update_wiki_pages.py | update_wiki_pages._get_stream_view_infos | def _get_stream_view_infos(
self,
trimmed=False):
"""query the sherlock-catalogues database streamed data tables' metadata
"""
self.log.debug('starting the ``_get_stream_view_infos`` method')
sqlQuery = u"""
SELECT * FROM crossmatch_catalogues.tcs_helper_catalogue_tables_info where legacy_table = 0 and table_name not like "legacy%%" and table_name like "%%stream" order by number_of_rows desc;
""" % locals()
streamInfo = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
if trimmed:
cleanTable = []
for r in streamInfo:
orow = collections.OrderedDict(sorted({}.items()))
for c in self.basicColumns:
if c in r:
orow[c] = r[c]
cleanTable.append(orow)
streamInfo = cleanTable
self.log.debug('completed the ``_get_stream_view_infos`` method')
return streamInfo | python | def _get_stream_view_infos(
self,
trimmed=False):
"""query the sherlock-catalogues database streamed data tables' metadata
"""
self.log.debug('starting the ``_get_stream_view_infos`` method')
sqlQuery = u"""
SELECT * FROM crossmatch_catalogues.tcs_helper_catalogue_tables_info where legacy_table = 0 and table_name not like "legacy%%" and table_name like "%%stream" order by number_of_rows desc;
""" % locals()
streamInfo = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.cataloguesDbConn,
quiet=False
)
if trimmed:
cleanTable = []
for r in streamInfo:
orow = collections.OrderedDict(sorted({}.items()))
for c in self.basicColumns:
if c in r:
orow[c] = r[c]
cleanTable.append(orow)
streamInfo = cleanTable
self.log.debug('completed the ``_get_stream_view_infos`` method')
return streamInfo | [
"def",
"_get_stream_view_infos",
"(",
"self",
",",
"trimmed",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_get_stream_view_infos`` method'",
")",
"sqlQuery",
"=",
"u\"\"\"\n SELECT * FROM crossmatch_catalogues.tcs_helper_catalogu... | query the sherlock-catalogues database streamed data tables' metadata | [
"query",
"the",
"sherlock",
"-",
"catalogues",
"database",
"streamed",
"data",
"tables",
"metadata"
] | 2c80fb6fa31b04e7820e6928e3d437a21e692dd3 | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L177-L205 | train | 49,797 |
kakulukia/django-undeletable | django_undeletable/models.py | AbstractUser.email_user | def email_user(
self, subject, message, from_email=settings.DEFAULT_FROM_EMAIL, **kwargs
):
"""
Sends an email to this User.
If settings.EMAIL_OVERRIDE_ADDRESS is set, this mail will be redirected to the alternate mail address.
"""
receiver = self.email
if settings.EMAIL_OVERRIDE_ADDRESS:
receiver = settings.EMAIL_OVERRIDE_ADDRESS
send_mail(subject, message, from_email, [receiver], **kwargs) | python | def email_user(
self, subject, message, from_email=settings.DEFAULT_FROM_EMAIL, **kwargs
):
"""
Sends an email to this User.
If settings.EMAIL_OVERRIDE_ADDRESS is set, this mail will be redirected to the alternate mail address.
"""
receiver = self.email
if settings.EMAIL_OVERRIDE_ADDRESS:
receiver = settings.EMAIL_OVERRIDE_ADDRESS
send_mail(subject, message, from_email, [receiver], **kwargs) | [
"def",
"email_user",
"(",
"self",
",",
"subject",
",",
"message",
",",
"from_email",
"=",
"settings",
".",
"DEFAULT_FROM_EMAIL",
",",
"*",
"*",
"kwargs",
")",
":",
"receiver",
"=",
"self",
".",
"email",
"if",
"settings",
".",
"EMAIL_OVERRIDE_ADDRESS",
":",
... | Sends an email to this User.
If settings.EMAIL_OVERRIDE_ADDRESS is set, this mail will be redirected to the alternate mail address. | [
"Sends",
"an",
"email",
"to",
"this",
"User",
".",
"If",
"settings",
".",
"EMAIL_OVERRIDE_ADDRESS",
"is",
"set",
"this",
"mail",
"will",
"be",
"redirected",
"to",
"the",
"alternate",
"mail",
"address",
"."
] | 565ae7c07ba0279a8cf768a96046f0f4ecbc0467 | https://github.com/kakulukia/django-undeletable/blob/565ae7c07ba0279a8cf768a96046f0f4ecbc0467/django_undeletable/models.py#L213-L225 | train | 49,798 |
Clinical-Genomics/trailblazer | trailblazer/cli/clean.py | clean | def clean(context, days_ago, yes):
"""Clean up files from "old" analyses runs."""
number_of_days_ago = dt.datetime.now() - dt.timedelta(days=days_ago)
analyses = context.obj['store'].analyses(
status='completed',
before=number_of_days_ago,
deleted=False,
)
for analysis_obj in analyses:
LOG.debug(f"checking analysis: {analysis_obj.family} ({analysis_obj.id})")
latest_analysis = context.obj['store'].analyses(family=analysis_obj.family).first()
if analysis_obj != latest_analysis:
print(click.style(f"{analysis_obj.family}: family has been re-started", fg='yellow'))
else:
print(f"delete analysis: {analysis_obj.family} ({analysis_obj.id})")
context.invoke(delete, analysis_id=analysis_obj.id, yes=yes) | python | def clean(context, days_ago, yes):
"""Clean up files from "old" analyses runs."""
number_of_days_ago = dt.datetime.now() - dt.timedelta(days=days_ago)
analyses = context.obj['store'].analyses(
status='completed',
before=number_of_days_ago,
deleted=False,
)
for analysis_obj in analyses:
LOG.debug(f"checking analysis: {analysis_obj.family} ({analysis_obj.id})")
latest_analysis = context.obj['store'].analyses(family=analysis_obj.family).first()
if analysis_obj != latest_analysis:
print(click.style(f"{analysis_obj.family}: family has been re-started", fg='yellow'))
else:
print(f"delete analysis: {analysis_obj.family} ({analysis_obj.id})")
context.invoke(delete, analysis_id=analysis_obj.id, yes=yes) | [
"def",
"clean",
"(",
"context",
",",
"days_ago",
",",
"yes",
")",
":",
"number_of_days_ago",
"=",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"dt",
".",
"timedelta",
"(",
"days",
"=",
"days_ago",
")",
"analyses",
"=",
"context",
".",
"obj",
"["... | Clean up files from "old" analyses runs. | [
"Clean",
"up",
"files",
"from",
"old",
"analyses",
"runs",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/cli/clean.py#L14-L29 | train | 49,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.