partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | linefit | Parameters
----------
y: 1D numpy array
The data to be fitted
x: 1D numpy array
The x values of the y array. x and y must
have the same shape.
weights: 1D numpy array, must have the same shape as x and y
weight values
Examples
--------
>>> import numpy as N... | lib/stsci/tools/linefit.py | def linefit(x, y, weights=None):
"""
Parameters
----------
y: 1D numpy array
The data to be fitted
x: 1D numpy array
The x values of the y array. x and y must
have the same shape.
weights: 1D numpy array, must have the same shape as x and y
weight values
E... | def linefit(x, y, weights=None):
"""
Parameters
----------
y: 1D numpy array
The data to be fitted
x: 1D numpy array
The x values of the y array. x and y must
have the same shape.
weights: 1D numpy array, must have the same shape as x and y
weight values
E... | [
"Parameters",
"----------",
"y",
":",
"1D",
"numpy",
"array",
"The",
"data",
"to",
"be",
"fitted",
"x",
":",
"1D",
"numpy",
"array",
"The",
"x",
"values",
"of",
"the",
"y",
"array",
".",
"x",
"and",
"y",
"must",
"have",
"the",
"same",
"shape",
".",
... | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/linefit.py#L19-L72 | [
"def",
"linefit",
"(",
"x",
",",
"y",
",",
"weights",
"=",
"None",
")",
":",
"if",
"len",
"(",
"x",
")",
"!=",
"len",
"(",
"y",
")",
":",
"print",
"(",
"\"Error: X and Y must have equal size\\n\"",
")",
"return",
"n",
"=",
"len",
"(",
"x",
")",
"w"... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Analyse.get | Analyses the measurement with the given parameters
:param measurementId:
:return: | backend/src/analyser/resources/analyse.py | def get(self, measurementId):
"""
Analyses the measurement with the given parameters
:param measurementId:
:return:
"""
logger.info('Analysing ' + measurementId)
measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.COMPLETE)
... | def get(self, measurementId):
"""
Analyses the measurement with the given parameters
:param measurementId:
:return:
"""
logger.info('Analysing ' + measurementId)
measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.COMPLETE)
... | [
"Analyses",
"the",
"measurement",
"with",
"the",
"given",
"parameters",
":",
"param",
"measurementId",
":",
":",
"return",
":"
] | 3ll3d00d/vibe | python | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/resources/analyse.py#L13-L49 | [
"def",
"get",
"(",
"self",
",",
"measurementId",
")",
":",
"logger",
".",
"info",
"(",
"'Analysing '",
"+",
"measurementId",
")",
"measurement",
"=",
"self",
".",
"_measurementController",
".",
"getMeasurement",
"(",
"measurementId",
",",
"MeasurementStatus",
".... | 124b029f13ac746723e92cb47e9cb56edd2e54b5 |
train | _applyTargetState | compares the current device state against the targetStateProvider and issues updates as necessary to ensure the
device is
at that state.
:param md:
:param targetState: the target state.
:param httpclient: the http client
:return: | backend/src/analyser/common/targetstatecontroller.py | def _applyTargetState(targetState, md, httpclient):
"""
compares the current device state against the targetStateProvider and issues updates as necessary to ensure the
device is
at that state.
:param md:
:param targetState: the target state.
:param httpclient: the http client
:return:
... | def _applyTargetState(targetState, md, httpclient):
"""
compares the current device state against the targetStateProvider and issues updates as necessary to ensure the
device is
at that state.
:param md:
:param targetState: the target state.
:param httpclient: the http client
:return:
... | [
"compares",
"the",
"current",
"device",
"state",
"against",
"the",
"targetStateProvider",
"and",
"issues",
"updates",
"as",
"necessary",
"to",
"ensure",
"the",
"device",
"is",
"at",
"that",
"state",
".",
":",
"param",
"md",
":",
":",
"param",
"targetState",
... | 3ll3d00d/vibe | python | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/common/targetstatecontroller.py#L78-L130 | [
"def",
"_applyTargetState",
"(",
"targetState",
",",
"md",
",",
"httpclient",
")",
":",
"anyUpdate",
"=",
"False",
"if",
"md",
"[",
"'fs'",
"]",
"!=",
"targetState",
".",
"fs",
":",
"logger",
".",
"info",
"(",
"\"Updating fs from \"",
"+",
"str",
"(",
"m... | 124b029f13ac746723e92cb47e9cb56edd2e54b5 |
train | TargetStateController.updateDeviceState | Updates the target state on the specified device.
:param targetState: the target state to reach.
:param device: the device to update.
:return: | backend/src/analyser/common/targetstatecontroller.py | def updateDeviceState(self, device):
"""
Updates the target state on the specified device.
:param targetState: the target state to reach.
:param device: the device to update.
:return:
"""
# this is only threadsafe because the targetstate is effectively immutable, ... | def updateDeviceState(self, device):
"""
Updates the target state on the specified device.
:param targetState: the target state to reach.
:param device: the device to update.
:return:
"""
# this is only threadsafe because the targetstate is effectively immutable, ... | [
"Updates",
"the",
"target",
"state",
"on",
"the",
"specified",
"device",
".",
":",
"param",
"targetState",
":",
"the",
"target",
"state",
"to",
"reach",
".",
":",
"param",
"device",
":",
"the",
"device",
"to",
"update",
".",
":",
"return",
":"
] | 3ll3d00d/vibe | python | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/common/targetstatecontroller.py#L25-L34 | [
"def",
"updateDeviceState",
"(",
"self",
",",
"device",
")",
":",
"# this is only threadsafe because the targetstate is effectively immutable, if it becomes mutable in future then",
"# funkiness may result",
"self",
".",
"_reactor",
".",
"offer",
"(",
"REACH_TARGET_STATE",
",",
"... | 124b029f13ac746723e92cb47e9cb56edd2e54b5 |
train | TargetStateController.updateTargetState | Updates the system target state and propagates that to all devices.
:param newState:
:return: | backend/src/analyser/common/targetstatecontroller.py | def updateTargetState(self, newState):
"""
Updates the system target state and propagates that to all devices.
:param newState:
:return:
"""
self._targetStateProvider.state = loadTargetState(newState, self._targetStateProvider.state)
for device in self.deviceContr... | def updateTargetState(self, newState):
"""
Updates the system target state and propagates that to all devices.
:param newState:
:return:
"""
self._targetStateProvider.state = loadTargetState(newState, self._targetStateProvider.state)
for device in self.deviceContr... | [
"Updates",
"the",
"system",
"target",
"state",
"and",
"propagates",
"that",
"to",
"all",
"devices",
".",
":",
"param",
"newState",
":",
":",
"return",
":"
] | 3ll3d00d/vibe | python | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/common/targetstatecontroller.py#L36-L44 | [
"def",
"updateTargetState",
"(",
"self",
",",
"newState",
")",
":",
"self",
".",
"_targetStateProvider",
".",
"state",
"=",
"loadTargetState",
"(",
"newState",
",",
"self",
".",
"_targetStateProvider",
".",
"state",
")",
"for",
"device",
"in",
"self",
".",
"... | 124b029f13ac746723e92cb47e9cb56edd2e54b5 |
train | convert | Input ASCII trailer file "input" will be read.
The contents will then be written out to a FITS file in the same format
as used by 'stwfits' from IRAF.
Parameters
===========
input : str
Filename of input ASCII trailer file
width : int
Number of characters wide to use for defin... | lib/stsci/tools/convertlog.py | def convert(input, width=132, output=None, keep=False):
"""Input ASCII trailer file "input" will be read.
The contents will then be written out to a FITS file in the same format
as used by 'stwfits' from IRAF.
Parameters
===========
input : str
Filename of input ASCII trailer file
... | def convert(input, width=132, output=None, keep=False):
"""Input ASCII trailer file "input" will be read.
The contents will then be written out to a FITS file in the same format
as used by 'stwfits' from IRAF.
Parameters
===========
input : str
Filename of input ASCII trailer file
... | [
"Input",
"ASCII",
"trailer",
"file",
"input",
"will",
"be",
"read",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/convertlog.py#L53-L112 | [
"def",
"convert",
"(",
"input",
",",
"width",
"=",
"132",
",",
"output",
"=",
"None",
",",
"keep",
"=",
"False",
")",
":",
"# open input trailer file",
"trl",
"=",
"open",
"(",
"input",
")",
"# process all lines",
"lines",
"=",
"np",
".",
"array",
"(",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | flatten_errors | An example function that will turn a nested dictionary of results
(as returned by ``ConfigObj.validate``) into a flat list.
``cfg`` is the ConfigObj instance being checked, ``res`` is the results
dictionary returned by ``validate``.
(This is a recursive function, so you shouldn't use the ``levels`` or... | lib/stsci/tools/configobj.py | def flatten_errors(cfg, res, levels=None, results=None):
"""
An example function that will turn a nested dictionary of results
(as returned by ``ConfigObj.validate``) into a flat list.
``cfg`` is the ConfigObj instance being checked, ``res`` is the results
dictionary returned by ``validate``.
... | def flatten_errors(cfg, res, levels=None, results=None):
"""
An example function that will turn a nested dictionary of results
(as returned by ``ConfigObj.validate``) into a flat list.
``cfg`` is the ConfigObj instance being checked, ``res`` is the results
dictionary returned by ``validate``.
... | [
"An",
"example",
"function",
"that",
"will",
"turn",
"a",
"nested",
"dictionary",
"of",
"results",
"(",
"as",
"returned",
"by",
"ConfigObj",
".",
"validate",
")",
"into",
"a",
"flat",
"list",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L2396-L2453 | [
"def",
"flatten_errors",
"(",
"cfg",
",",
"res",
",",
"levels",
"=",
"None",
",",
"results",
"=",
"None",
")",
":",
"if",
"levels",
"is",
"None",
":",
"# first time called",
"levels",
"=",
"[",
"]",
"results",
"=",
"[",
"]",
"if",
"res",
"==",
"True"... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | get_extra_values | Find all the values and sections not in the configspec from a validated
ConfigObj.
``get_extra_values`` returns a list of tuples where each tuple represents
either an extra section, or an extra value.
The tuples contain two values, a tuple representing the section the value
is in and the name of t... | lib/stsci/tools/configobj.py | def get_extra_values(conf, _prepend=()):
"""
Find all the values and sections not in the configspec from a validated
ConfigObj.
``get_extra_values`` returns a list of tuples where each tuple represents
either an extra section, or an extra value.
The tuples contain two values, a tuple represent... | def get_extra_values(conf, _prepend=()):
"""
Find all the values and sections not in the configspec from a validated
ConfigObj.
``get_extra_values`` returns a list of tuples where each tuple represents
either an extra section, or an extra value.
The tuples contain two values, a tuple represent... | [
"Find",
"all",
"the",
"values",
"and",
"sections",
"not",
"in",
"the",
"configspec",
"from",
"a",
"validated",
"ConfigObj",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L2456-L2479 | [
"def",
"get_extra_values",
"(",
"conf",
",",
"_prepend",
"=",
"(",
")",
")",
":",
"out",
"=",
"[",
"]",
"out",
".",
"extend",
"(",
"[",
"(",
"_prepend",
",",
"name",
")",
"for",
"name",
"in",
"conf",
".",
"extra_values",
"]",
")",
"for",
"name",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | InterpolationEngine._fetch | Helper function to fetch values from owning section.
Returns a 2-tuple: the value, and the section where it was found. | lib/stsci/tools/configobj.py | def _fetch(self, key):
"""Helper function to fetch values from owning section.
Returns a 2-tuple: the value, and the section where it was found.
"""
# switch off interpolation before we try and fetch anything !
save_interp = self.section.main.interpolation
self.section.m... | def _fetch(self, key):
"""Helper function to fetch values from owning section.
Returns a 2-tuple: the value, and the section where it was found.
"""
# switch off interpolation before we try and fetch anything !
save_interp = self.section.main.interpolation
self.section.m... | [
"Helper",
"function",
"to",
"fetch",
"values",
"from",
"owning",
"section",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L381-L412 | [
"def",
"_fetch",
"(",
"self",
",",
"key",
")",
":",
"# switch off interpolation before we try and fetch anything !",
"save_interp",
"=",
"self",
".",
"section",
".",
"main",
".",
"interpolation",
"self",
".",
"section",
".",
"main",
".",
"interpolation",
"=",
"Fal... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.pop | 'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised' | lib/stsci/tools/configobj.py | def pop(self, key, default=MISSING):
"""
'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised'
"""
try:
val = self[key]
except KeyError:
if default is... | def pop(self, key, default=MISSING):
"""
'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised'
"""
try:
val = self[key]
except KeyError:
if default is... | [
"D",
".",
"pop",
"(",
"k",
"[",
"d",
"]",
")",
"-",
">",
"v",
"remove",
"specified",
"key",
"and",
"return",
"the",
"corresponding",
"value",
".",
"If",
"key",
"is",
"not",
"found",
"d",
"is",
"returned",
"if",
"given",
"otherwise",
"KeyError",
"is",... | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L680-L693 | [
"def",
"pop",
"(",
"self",
",",
"key",
",",
"default",
"=",
"MISSING",
")",
":",
"try",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"if",
"default",
"is",
"MISSING",
":",
"raise",
"val",
"=",
"default",
"else",
":",
"del",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.popitem | Pops the first (key,val) | lib/stsci/tools/configobj.py | def popitem(self):
"""Pops the first (key,val)"""
sequence = (self.scalars + self.sections)
if not sequence:
raise KeyError(": 'popitem(): dictionary is empty'")
key = sequence[0]
val = self[key]
del self[key]
return key, val | def popitem(self):
"""Pops the first (key,val)"""
sequence = (self.scalars + self.sections)
if not sequence:
raise KeyError(": 'popitem(): dictionary is empty'")
key = sequence[0]
val = self[key]
del self[key]
return key, val | [
"Pops",
"the",
"first",
"(",
"key",
"val",
")"
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L696-L704 | [
"def",
"popitem",
"(",
"self",
")",
":",
"sequence",
"=",
"(",
"self",
".",
"scalars",
"+",
"self",
".",
"sections",
")",
"if",
"not",
"sequence",
":",
"raise",
"KeyError",
"(",
"\": 'popitem(): dictionary is empty'\"",
")",
"key",
"=",
"sequence",
"[",
"0... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.clear | A version of clear that also affects scalars/sections
Also clears comments and configspec.
Leaves other attributes alone :
depth/main/parent are not affected | lib/stsci/tools/configobj.py | def clear(self):
"""
A version of clear that also affects scalars/sections
Also clears comments and configspec.
Leaves other attributes alone :
depth/main/parent are not affected
"""
dict.clear(self)
self.scalars = []
self.sections = []
... | def clear(self):
"""
A version of clear that also affects scalars/sections
Also clears comments and configspec.
Leaves other attributes alone :
depth/main/parent are not affected
"""
dict.clear(self)
self.scalars = []
self.sections = []
... | [
"A",
"version",
"of",
"clear",
"that",
"also",
"affects",
"scalars",
"/",
"sections",
"Also",
"clears",
"comments",
"and",
"configspec",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L707-L722 | [
"def",
"clear",
"(",
"self",
")",
":",
"dict",
".",
"clear",
"(",
"self",
")",
"self",
".",
"scalars",
"=",
"[",
"]",
"self",
".",
"sections",
"=",
"[",
"]",
"self",
".",
"comments",
"=",
"{",
"}",
"self",
".",
"inline_comments",
"=",
"{",
"}",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.items | D.items() -> list of D's (key, value) pairs, as 2-tuples | lib/stsci/tools/configobj.py | def items(self):
"""D.items() -> list of D's (key, value) pairs, as 2-tuples"""
return list(zip((self.scalars + self.sections), list(self.values()))) | def items(self):
"""D.items() -> list of D's (key, value) pairs, as 2-tuples"""
return list(zip((self.scalars + self.sections), list(self.values()))) | [
"D",
".",
"items",
"()",
"-",
">",
"list",
"of",
"D",
"s",
"(",
"key",
"value",
")",
"pairs",
"as",
"2",
"-",
"tuples"
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L734-L736 | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"list",
"(",
"zip",
"(",
"(",
"self",
".",
"scalars",
"+",
"self",
".",
"sections",
")",
",",
"list",
"(",
"self",
".",
"values",
"(",
")",
")",
")",
")"
] | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.dict | Return a deepcopy of self as a dictionary.
All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.
>>> n = a.dict() # doctest: +SKIP
>>> n == a # doctest: +SKIP
1
>>> n is a # doctest: +SKIP
... | lib/stsci/tools/configobj.py | def dict(self):
"""
Return a deepcopy of self as a dictionary.
All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.
>>> n = a.dict() # doctest: +SKIP
>>> n == a # doctest: +SKIP
1
... | def dict(self):
"""
Return a deepcopy of self as a dictionary.
All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.
>>> n = a.dict() # doctest: +SKIP
>>> n == a # doctest: +SKIP
1
... | [
"Return",
"a",
"deepcopy",
"of",
"self",
"as",
"a",
"dictionary",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L782-L807 | [
"def",
"dict",
"(",
"self",
")",
":",
"newdict",
"=",
"{",
"}",
"for",
"entry",
"in",
"self",
":",
"this_entry",
"=",
"self",
"[",
"entry",
"]",
"if",
"isinstance",
"(",
"this_entry",
",",
"Section",
")",
":",
"this_entry",
"=",
"this_entry",
".",
"d... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.merge | A recursive update - useful for merging config files.
>>> a = '''[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file'''.splitlines()
>>> b = '''# File is user.ini
... [section1]
... option1 =... | lib/stsci/tools/configobj.py | def merge(self, indict):
"""
A recursive update - useful for merging config files.
>>> a = '''[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file'''.splitlines()
>>> b = '''# File is user.ini
... | def merge(self, indict):
"""
A recursive update - useful for merging config files.
>>> a = '''[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file'''.splitlines()
>>> b = '''# File is user.ini
... | [
"A",
"recursive",
"update",
"-",
"useful",
"for",
"merging",
"config",
"files",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L810-L834 | [
"def",
"merge",
"(",
"self",
",",
"indict",
")",
":",
"for",
"key",
",",
"val",
"in",
"list",
"(",
"indict",
".",
"items",
"(",
")",
")",
":",
"if",
"(",
"key",
"in",
"self",
"and",
"isinstance",
"(",
"self",
"[",
"key",
"]",
",",
"dict",
")",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.rename | Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)
Also renames comments. | lib/stsci/tools/configobj.py | def rename(self, oldkey, newkey):
"""
Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)
Also renames comments.
"""
if oldkey in self.scal... | def rename(self, oldkey, newkey):
"""
Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)
Also renames comments.
"""
if oldkey in self.scal... | [
"Change",
"a",
"keyname",
"to",
"another",
"without",
"changing",
"position",
"in",
"sequence",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L837-L864 | [
"def",
"rename",
"(",
"self",
",",
"oldkey",
",",
"newkey",
")",
":",
"if",
"oldkey",
"in",
"self",
".",
"scalars",
":",
"the_list",
"=",
"self",
".",
"scalars",
"elif",
"oldkey",
"in",
"self",
".",
"sections",
":",
"the_list",
"=",
"self",
".",
"sec... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.walk | Walk every member and call a function on the keyword and value.
Return a dictionary of the return values
If the function raises an exception, raise the errror
unless ``raise_errors=False``, in which case set the return value to
``False``.
Any unrecognised keyword arguments you... | lib/stsci/tools/configobj.py | def walk(self, function, raise_errors=True,
call_on_sections=False, **keywargs):
"""
Walk every member and call a function on the keyword and value.
Return a dictionary of the return values
If the function raises an exception, raise the errror
unless ``raise_errors=... | def walk(self, function, raise_errors=True,
call_on_sections=False, **keywargs):
"""
Walk every member and call a function on the keyword and value.
Return a dictionary of the return values
If the function raises an exception, raise the errror
unless ``raise_errors=... | [
"Walk",
"every",
"member",
"and",
"call",
"a",
"function",
"on",
"the",
"keyword",
"and",
"value",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L867-L949 | [
"def",
"walk",
"(",
"self",
",",
"function",
",",
"raise_errors",
"=",
"True",
",",
"call_on_sections",
"=",
"False",
",",
"*",
"*",
"keywargs",
")",
":",
"out",
"=",
"{",
"}",
"# scalars first",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.as_bool | Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
``True``.
If the string is one ... | lib/stsci/tools/configobj.py | def as_bool(self, key):
"""
Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
... | def as_bool(self, key):
"""
Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
... | [
"Accepts",
"a",
"key",
"as",
"input",
".",
"The",
"corresponding",
"value",
"must",
"be",
"a",
"string",
"or",
"the",
"objects",
"(",
"True",
"or",
"1",
")",
"or",
"(",
"False",
"or",
"0",
")",
".",
"We",
"allow",
"0",
"and",
"1",
"to",
"retain",
... | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L952-L993 | [
"def",
"as_bool",
"(",
"self",
",",
"key",
")",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"if",
"val",
"==",
"True",
":",
"return",
"True",
"elif",
"val",
"==",
"False",
":",
"return",
"False",
"else",
":",
"try",
":",
"if",
"not",
"isinstance",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.as_list | A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a['a'] = 1
>>> a.as_list('a')
[1]
>>> a['a'] = (1,)
>>> a.as_list('a')
[1]
>>> a['a'] = [1]
>>> a.as_list('a')
[1] | lib/stsci/tools/configobj.py | def as_list(self, key):
"""
A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a['a'] = 1
>>> a.as_list('a')
[1]
>>> a['a'] = (1,)
>>> a.as_list('a')
[1]
>>> a['a'] = [1]... | def as_list(self, key):
"""
A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a['a'] = 1
>>> a.as_list('a')
[1]
>>> a['a'] = (1,)
>>> a.as_list('a')
[1]
>>> a['a'] = [1]... | [
"A",
"convenience",
"method",
"which",
"fetches",
"the",
"specified",
"value",
"guaranteeing",
"that",
"it",
"is",
"a",
"list",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1039-L1058 | [
"def",
"as_list",
"(",
"self",
",",
"key",
")",
":",
"result",
"=",
"self",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"result",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"list",
"(",
"result",
")",
"return",
"[",
"result",
"]"
] | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.restore_default | Restore (and return) default value for the specified key.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
If there is no default value for this key, ``KeyError`` is raised. | lib/stsci/tools/configobj.py | def restore_default(self, key):
"""
Restore (and return) default value for the specified key.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
If there is no default value for this key, ``KeyError`` is raised.
"""
... | def restore_default(self, key):
"""
Restore (and return) default value for the specified key.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
If there is no default value for this key, ``KeyError`` is raised.
"""
... | [
"Restore",
"(",
"and",
"return",
")",
"default",
"value",
"for",
"the",
"specified",
"key",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1061-L1074 | [
"def",
"restore_default",
"(",
"self",
",",
"key",
")",
":",
"default",
"=",
"self",
".",
"default_values",
"[",
"key",
"]",
"dict",
".",
"__setitem__",
"(",
"self",
",",
"key",
",",
"default",
")",
"if",
"key",
"not",
"in",
"self",
".",
"defaults",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | Section.restore_defaults | Recursively restore default values to all members
that have them.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
It doesn't delete or modify entries without default values. | lib/stsci/tools/configobj.py | def restore_defaults(self):
"""
Recursively restore default values to all members
that have them.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
It doesn't delete or modify entries without default values.
""... | def restore_defaults(self):
"""
Recursively restore default values to all members
that have them.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
It doesn't delete or modify entries without default values.
""... | [
"Recursively",
"restore",
"default",
"values",
"to",
"all",
"members",
"that",
"have",
"them",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1077-L1091 | [
"def",
"restore_defaults",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"default_values",
":",
"self",
".",
"restore_default",
"(",
"key",
")",
"for",
"section",
"in",
"self",
".",
"sections",
":",
"self",
"[",
"section",
"]",
".",
"restore_de... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._handle_bom | Handle any BOM, and decode if necessary.
If an encoding is specified, that *must* be used - but the BOM should
still be removed (and the BOM attribute set).
(If the encoding is wrongly specified, then a BOM for an alternative
encoding won't be discovered or removed.)
If an enc... | lib/stsci/tools/configobj.py | def _handle_bom(self, infile):
"""
Handle any BOM, and decode if necessary.
If an encoding is specified, that *must* be used - but the BOM should
still be removed (and the BOM attribute set).
(If the encoding is wrongly specified, then a BOM for an alternative
encoding ... | def _handle_bom(self, infile):
"""
Handle any BOM, and decode if necessary.
If an encoding is specified, that *must* be used - but the BOM should
still be removed (and the BOM attribute set).
(If the encoding is wrongly specified, then a BOM for an alternative
encoding ... | [
"Handle",
"any",
"BOM",
"and",
"decode",
"if",
"necessary",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1395-L1493 | [
"def",
"_handle_bom",
"(",
"self",
",",
"infile",
")",
":",
"if",
"(",
"(",
"self",
".",
"encoding",
"is",
"not",
"None",
")",
"and",
"(",
"self",
".",
"encoding",
".",
"lower",
"(",
")",
"not",
"in",
"BOM_LIST",
")",
")",
":",
"# No need to check fo... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._decode | Decode infile to unicode. Using the specified encoding.
if is a string, it also needs converting to a list. | lib/stsci/tools/configobj.py | def _decode(self, infile, encoding):
"""
Decode infile to unicode. Using the specified encoding.
if is a string, it also needs converting to a list.
"""
if isinstance(infile, string_types):
# can't be unicode
# NOTE: Could raise a ``UnicodeDecodeError``
... | def _decode(self, infile, encoding):
"""
Decode infile to unicode. Using the specified encoding.
if is a string, it also needs converting to a list.
"""
if isinstance(infile, string_types):
# can't be unicode
# NOTE: Could raise a ``UnicodeDecodeError``
... | [
"Decode",
"infile",
"to",
"unicode",
".",
"Using",
"the",
"specified",
"encoding",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1504-L1524 | [
"def",
"_decode",
"(",
"self",
",",
"infile",
",",
"encoding",
")",
":",
"if",
"isinstance",
"(",
"infile",
",",
"string_types",
")",
":",
"# can't be unicode",
"# NOTE: Could raise a ``UnicodeDecodeError``",
"return",
"infile",
".",
"decode",
"(",
"encoding",
")"... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._decode_element | Decode element to unicode if necessary. | lib/stsci/tools/configobj.py | def _decode_element(self, line):
"""Decode element to unicode if necessary."""
if not self.encoding:
return line
if isinstance(line, str) and self.default_encoding:
return line.decode(self.default_encoding)
return line | def _decode_element(self, line):
"""Decode element to unicode if necessary."""
if not self.encoding:
return line
if isinstance(line, str) and self.default_encoding:
return line.decode(self.default_encoding)
return line | [
"Decode",
"element",
"to",
"unicode",
"if",
"necessary",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1527-L1533 | [
"def",
"_decode_element",
"(",
"self",
",",
"line",
")",
":",
"if",
"not",
"self",
".",
"encoding",
":",
"return",
"line",
"if",
"isinstance",
"(",
"line",
",",
"str",
")",
"and",
"self",
".",
"default_encoding",
":",
"return",
"line",
".",
"decode",
"... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._parse | Actually parse the config file. | lib/stsci/tools/configobj.py | def _parse(self, infile):
"""Actually parse the config file."""
temp_list_values = self.list_values
if self.unrepr:
self.list_values = False
comment_list = []
done_start = False
this_section = self
maxline = len(infile) - 1
cur_index = -1
... | def _parse(self, infile):
"""Actually parse the config file."""
temp_list_values = self.list_values
if self.unrepr:
self.list_values = False
comment_list = []
done_start = False
this_section = self
maxline = len(infile) - 1
cur_index = -1
... | [
"Actually",
"parse",
"the",
"config",
"file",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1547-L1712 | [
"def",
"_parse",
"(",
"self",
",",
"infile",
")",
":",
"temp_list_values",
"=",
"self",
".",
"list_values",
"if",
"self",
".",
"unrepr",
":",
"self",
".",
"list_values",
"=",
"False",
"comment_list",
"=",
"[",
"]",
"done_start",
"=",
"False",
"this_section... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._match_depth | Given a section and a depth level, walk back through the sections
parents to see if the depth level matches a previous section.
Return a reference to the right section,
or raise a SyntaxError. | lib/stsci/tools/configobj.py | def _match_depth(self, sect, depth):
"""
Given a section and a depth level, walk back through the sections
parents to see if the depth level matches a previous section.
Return a reference to the right section,
or raise a SyntaxError.
"""
while depth < sect.depth:... | def _match_depth(self, sect, depth):
"""
Given a section and a depth level, walk back through the sections
parents to see if the depth level matches a previous section.
Return a reference to the right section,
or raise a SyntaxError.
"""
while depth < sect.depth:... | [
"Given",
"a",
"section",
"and",
"a",
"depth",
"level",
"walk",
"back",
"through",
"the",
"sections",
"parents",
"to",
"see",
"if",
"the",
"depth",
"level",
"matches",
"a",
"previous",
"section",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1715-L1731 | [
"def",
"_match_depth",
"(",
"self",
",",
"sect",
",",
"depth",
")",
":",
"while",
"depth",
"<",
"sect",
".",
"depth",
":",
"if",
"sect",
"is",
"sect",
".",
"parent",
":",
"# we've reached the top level already",
"raise",
"SyntaxError",
"(",
")",
"sect",
"=... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._handle_error | Handle an error according to the error settings.
Either raise the error or store it.
The error will have occured at ``cur_index`` | lib/stsci/tools/configobj.py | def _handle_error(self, text, ErrorClass, infile, cur_index):
"""
Handle an error according to the error settings.
Either raise the error or store it.
The error will have occured at ``cur_index``
"""
line = infile[cur_index]
cur_index += 1
message = text ... | def _handle_error(self, text, ErrorClass, infile, cur_index):
"""
Handle an error according to the error settings.
Either raise the error or store it.
The error will have occured at ``cur_index``
"""
line = infile[cur_index]
cur_index += 1
message = text ... | [
"Handle",
"an",
"error",
"according",
"to",
"the",
"error",
"settings",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1734-L1750 | [
"def",
"_handle_error",
"(",
"self",
",",
"text",
",",
"ErrorClass",
",",
"infile",
",",
"cur_index",
")",
":",
"line",
"=",
"infile",
"[",
"cur_index",
"]",
"cur_index",
"+=",
"1",
"message",
"=",
"text",
"%",
"cur_index",
"error",
"=",
"ErrorClass",
"(... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._unquote | Return an unquoted version of a value | lib/stsci/tools/configobj.py | def _unquote(self, value):
"""Return an unquoted version of a value"""
if not value:
# should only happen during parsing of lists
raise SyntaxError
if (value[0] == value[-1]) and (value[0] in ('"', "'")):
value = value[1:-1]
return value | def _unquote(self, value):
"""Return an unquoted version of a value"""
if not value:
# should only happen during parsing of lists
raise SyntaxError
if (value[0] == value[-1]) and (value[0] in ('"', "'")):
value = value[1:-1]
return value | [
"Return",
"an",
"unquoted",
"version",
"of",
"a",
"value"
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1753-L1760 | [
"def",
"_unquote",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"# should only happen during parsing of lists",
"raise",
"SyntaxError",
"if",
"(",
"value",
"[",
"0",
"]",
"==",
"value",
"[",
"-",
"1",
"]",
")",
"and",
"(",
"value",
"["... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._quote | Return a safely quoted version of a value.
Raise a ConfigObjError if the value cannot be safely quoted.
If multiline is ``True`` (default) then use triple quotes
if necessary.
* Don't quote values that don't need it.
* Recursively quote members of a list and return a comma join... | lib/stsci/tools/configobj.py | def _quote(self, value, multiline=True):
"""
Return a safely quoted version of a value.
Raise a ConfigObjError if the value cannot be safely quoted.
If multiline is ``True`` (default) then use triple quotes
if necessary.
* Don't quote values that don't need it.
... | def _quote(self, value, multiline=True):
"""
Return a safely quoted version of a value.
Raise a ConfigObjError if the value cannot be safely quoted.
If multiline is ``True`` (default) then use triple quotes
if necessary.
* Don't quote values that don't need it.
... | [
"Return",
"a",
"safely",
"quoted",
"version",
"of",
"a",
"value",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1763-L1829 | [
"def",
"_quote",
"(",
"self",
",",
"value",
",",
"multiline",
"=",
"True",
")",
":",
"if",
"multiline",
"and",
"self",
".",
"write_empty_values",
"and",
"value",
"==",
"''",
":",
"# Only if multiline is set, so that it is used for values not",
"# keys, and not values ... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._handle_value | Given a value string, unquote, remove comment,
handle lists. (including empty and single member lists) | lib/stsci/tools/configobj.py | def _handle_value(self, value):
"""
Given a value string, unquote, remove comment,
handle lists. (including empty and single member lists)
"""
if self._inspec:
# Parsing a configspec so don't handle comments
return (value, '')
# do we look for list... | def _handle_value(self, value):
"""
Given a value string, unquote, remove comment,
handle lists. (including empty and single member lists)
"""
if self._inspec:
# Parsing a configspec so don't handle comments
return (value, '')
# do we look for list... | [
"Given",
"a",
"value",
"string",
"unquote",
"remove",
"comment",
"handle",
"lists",
".",
"(",
"including",
"empty",
"and",
"single",
"member",
"lists",
")"
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1852-L1898 | [
"def",
"_handle_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_inspec",
":",
"# Parsing a configspec so don't handle comments",
"return",
"(",
"value",
",",
"''",
")",
"# do we look for lists in values ?",
"if",
"not",
"self",
".",
"list_values",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._multiline | Extract the value, where we are in a multiline situation. | lib/stsci/tools/configobj.py | def _multiline(self, value, infile, cur_index, maxline):
"""Extract the value, where we are in a multiline situation."""
quot = value[:3]
newvalue = value[3:]
single_line = self._triple_quote[quot][0]
multi_line = self._triple_quote[quot][1]
mat = single_line.match(value)... | def _multiline(self, value, infile, cur_index, maxline):
"""Extract the value, where we are in a multiline situation."""
quot = value[:3]
newvalue = value[3:]
single_line = self._triple_quote[quot][0]
multi_line = self._triple_quote[quot][1]
mat = single_line.match(value)... | [
"Extract",
"the",
"value",
"where",
"we",
"are",
"in",
"a",
"multiline",
"situation",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1901-L1933 | [
"def",
"_multiline",
"(",
"self",
",",
"value",
",",
"infile",
",",
"cur_index",
",",
"maxline",
")",
":",
"quot",
"=",
"value",
"[",
":",
"3",
"]",
"newvalue",
"=",
"value",
"[",
"3",
":",
"]",
"single_line",
"=",
"self",
".",
"_triple_quote",
"[",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._handle_configspec | Parse the configspec. | lib/stsci/tools/configobj.py | def _handle_configspec(self, configspec):
"""Parse the configspec."""
# FIXME: Should we check that the configspec was created with the
# correct settings ? (i.e. ``list_values=False``)
if not isinstance(configspec, ConfigObj):
try:
configspec = ConfigO... | def _handle_configspec(self, configspec):
"""Parse the configspec."""
# FIXME: Should we check that the configspec was created with the
# correct settings ? (i.e. ``list_values=False``)
if not isinstance(configspec, ConfigObj):
try:
configspec = ConfigO... | [
"Parse",
"the",
"configspec",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1936-L1953 | [
"def",
"_handle_configspec",
"(",
"self",
",",
"configspec",
")",
":",
"# FIXME: Should we check that the configspec was created with the",
"# correct settings ? (i.e. ``list_values=False``)",
"if",
"not",
"isinstance",
"(",
"configspec",
",",
"ConfigObj",
")",
":",
"try... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._set_configspec | Called by validate. Handles setting the configspec on subsections
including sections to be validated by __many__ | lib/stsci/tools/configobj.py | def _set_configspec(self, section, copy):
"""
Called by validate. Handles setting the configspec on subsections
including sections to be validated by __many__
"""
configspec = section.configspec
many = configspec.get('__many__')
if isinstance(many, dict):
... | def _set_configspec(self, section, copy):
"""
Called by validate. Handles setting the configspec on subsections
including sections to be validated by __many__
"""
configspec = section.configspec
many = configspec.get('__many__')
if isinstance(many, dict):
... | [
"Called",
"by",
"validate",
".",
"Handles",
"setting",
"the",
"configspec",
"on",
"subsections",
"including",
"sections",
"to",
"be",
"validated",
"by",
"__many__"
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1957-L1982 | [
"def",
"_set_configspec",
"(",
"self",
",",
"section",
",",
"copy",
")",
":",
"configspec",
"=",
"section",
".",
"configspec",
"many",
"=",
"configspec",
".",
"get",
"(",
"'__many__'",
")",
"if",
"isinstance",
"(",
"many",
",",
"dict",
")",
":",
"for",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._write_line | Write an individual line, for the write method | lib/stsci/tools/configobj.py | def _write_line(self, indent_string, entry, this_entry, comment):
"""Write an individual line, for the write method"""
# NOTE: the calls to self._quote here handles non-StringType values.
if not self.unrepr:
val = self._decode_element(self._quote(this_entry))
else:
... | def _write_line(self, indent_string, entry, this_entry, comment):
"""Write an individual line, for the write method"""
# NOTE: the calls to self._quote here handles non-StringType values.
if not self.unrepr:
val = self._decode_element(self._quote(this_entry))
else:
... | [
"Write",
"an",
"individual",
"line",
"for",
"the",
"write",
"method"
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1985-L1996 | [
"def",
"_write_line",
"(",
"self",
",",
"indent_string",
",",
"entry",
",",
"this_entry",
",",
"comment",
")",
":",
"# NOTE: the calls to self._quote here handles non-StringType values.",
"if",
"not",
"self",
".",
"unrepr",
":",
"val",
"=",
"self",
".",
"_decode_ele... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._write_marker | Write a section marker line | lib/stsci/tools/configobj.py | def _write_marker(self, indent_string, depth, entry, comment):
"""Write a section marker line"""
return '%s%s%s%s%s' % (indent_string,
self._a_to_u('[' * depth),
self._quote(self._decode_element(entry), multiline=False),
... | def _write_marker(self, indent_string, depth, entry, comment):
"""Write a section marker line"""
return '%s%s%s%s%s' % (indent_string,
self._a_to_u('[' * depth),
self._quote(self._decode_element(entry), multiline=False),
... | [
"Write",
"a",
"section",
"marker",
"line"
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L1999-L2005 | [
"def",
"_write_marker",
"(",
"self",
",",
"indent_string",
",",
"depth",
",",
"entry",
",",
"comment",
")",
":",
"return",
"'%s%s%s%s%s'",
"%",
"(",
"indent_string",
",",
"self",
".",
"_a_to_u",
"(",
"'['",
"*",
"depth",
")",
",",
"self",
".",
"_quote",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj._handle_comment | Deal with a comment. | lib/stsci/tools/configobj.py | def _handle_comment(self, comment):
"""Deal with a comment."""
if not comment:
return ''
start = self.indent_type
if not comment.startswith('#'):
start += self._a_to_u(' # ')
return (start + comment) | def _handle_comment(self, comment):
"""Deal with a comment."""
if not comment:
return ''
start = self.indent_type
if not comment.startswith('#'):
start += self._a_to_u(' # ')
return (start + comment) | [
"Deal",
"with",
"a",
"comment",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L2008-L2015 | [
"def",
"_handle_comment",
"(",
"self",
",",
"comment",
")",
":",
"if",
"not",
"comment",
":",
"return",
"''",
"start",
"=",
"self",
".",
"indent_type",
"if",
"not",
"comment",
".",
"startswith",
"(",
"'#'",
")",
":",
"start",
"+=",
"self",
".",
"_a_to_... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj.write | Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename # doctest: +SKIP
>>> a.filename = 'test.ini' # doctest: +SKIP
>>> a.write() # doctest: +SKIP
>>> a.filename = filename # doctest: +SKIP
>>> a == Con... | lib/stsci/tools/configobj.py | def write(self, outfile=None, section=None):
"""
Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename # doctest: +SKIP
>>> a.filename = 'test.ini' # doctest: +SKIP
>>> a.write() # doctest: +SKIP
... | def write(self, outfile=None, section=None):
"""
Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename # doctest: +SKIP
>>> a.filename = 'test.ini' # doctest: +SKIP
>>> a.write() # doctest: +SKIP
... | [
"Write",
"the",
"current",
"ConfigObj",
"as",
"a",
"file"
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L2020-L2128 | [
"def",
"write",
"(",
"self",
",",
"outfile",
"=",
"None",
",",
"section",
"=",
"None",
")",
":",
"if",
"self",
".",
"indent_type",
"is",
"None",
":",
"# this can be true if initialised from a dictionary",
"self",
".",
"indent_type",
"=",
"DEFAULT_INDENT_TYPE",
"... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj.validate | Test the ConfigObj against a configspec.
It uses the ``validator`` object from *validate.py*.
To run ``validate`` on the current ConfigObj, call: ::
test = config.validate(validator)
(Normally having previously passed in the configspec when the ConfigObj
was created - you... | lib/stsci/tools/configobj.py | def validate(self, validator, preserve_errors=False, copy=False,
section=None):
"""
Test the ConfigObj against a configspec.
It uses the ``validator`` object from *validate.py*.
To run ``validate`` on the current ConfigObj, call: ::
test = config.validate(... | def validate(self, validator, preserve_errors=False, copy=False,
section=None):
"""
Test the ConfigObj against a configspec.
It uses the ``validator`` object from *validate.py*.
To run ``validate`` on the current ConfigObj, call: ::
test = config.validate(... | [
"Test",
"the",
"ConfigObj",
"against",
"a",
"configspec",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L2130-L2334 | [
"def",
"validate",
"(",
"self",
",",
"validator",
",",
"preserve_errors",
"=",
"False",
",",
"copy",
"=",
"False",
",",
"section",
"=",
"None",
")",
":",
"if",
"section",
"is",
"None",
":",
"if",
"self",
".",
"configspec",
"is",
"None",
":",
"raise",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj.reset | Clear ConfigObj instance and restore to 'freshly created' state. | lib/stsci/tools/configobj.py | def reset(self):
"""Clear ConfigObj instance and restore to 'freshly created' state."""
self.clear()
self._initialise()
# FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
# requires an empty dictionary
self.configspec = None
# ... | def reset(self):
"""Clear ConfigObj instance and restore to 'freshly created' state."""
self.clear()
self._initialise()
# FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
# requires an empty dictionary
self.configspec = None
# ... | [
"Clear",
"ConfigObj",
"instance",
"and",
"restore",
"to",
"freshly",
"created",
"state",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L2337-L2345 | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"_initialise",
"(",
")",
"# FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)",
"# requires an empty dictionary",
"self",
".",
"configspec",
"=",
"None"... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | ConfigObj.reload | Reload a ConfigObj from file.
This method raises a ``ReloadError`` if the ConfigObj doesn't have
a filename attribute pointing to a file. | lib/stsci/tools/configobj.py | def reload(self):
"""
Reload a ConfigObj from file.
This method raises a ``ReloadError`` if the ConfigObj doesn't have
a filename attribute pointing to a file.
"""
if not isinstance(self.filename, string_types):
raise ReloadError()
filename = self.fi... | def reload(self):
"""
Reload a ConfigObj from file.
This method raises a ``ReloadError`` if the ConfigObj doesn't have
a filename attribute pointing to a file.
"""
if not isinstance(self.filename, string_types):
raise ReloadError()
filename = self.fi... | [
"Reload",
"a",
"ConfigObj",
"from",
"file",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L2348-L2370 | [
"def",
"reload",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"filename",
",",
"string_types",
")",
":",
"raise",
"ReloadError",
"(",
")",
"filename",
"=",
"self",
".",
"filename",
"current_options",
"=",
"{",
"}",
"for",
"entry",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | SimpleVal.check | A dummy check method, always returns the value unchanged. | lib/stsci/tools/configobj.py | def check(self, check, member, missing=False):
"""A dummy check method, always returns the value unchanged."""
if missing:
raise self.baseErrorClass()
return member | def check(self, check, member, missing=False):
"""A dummy check method, always returns the value unchanged."""
if missing:
raise self.baseErrorClass()
return member | [
"A",
"dummy",
"check",
"method",
"always",
"returns",
"the",
"value",
"unchanged",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/configobj.py#L2389-L2393 | [
"def",
"check",
"(",
"self",
",",
"check",
",",
"member",
",",
"missing",
"=",
"False",
")",
":",
"if",
"missing",
":",
"raise",
"self",
".",
"baseErrorClass",
"(",
")",
"return",
"member"
] | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | _processCommandLineArgs | Get the command line arguments
Parameters: NONE
Returns:
files list of file specifications to be converted
outputFileNames list of output file specifications
(one per input file)
Default: a list of None value... | lib/stsci/tools/convertwaiveredfits.py | def _processCommandLineArgs():
"""
Get the command line arguments
Parameters: NONE
Returns:
files list of file specifications to be converted
outputFileNames list of output file specifications
(one per input file)
... | def _processCommandLineArgs():
"""
Get the command line arguments
Parameters: NONE
Returns:
files list of file specifications to be converted
outputFileNames list of output file specifications
(one per input file)
... | [
"Get",
"the",
"command",
"line",
"arguments"
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/convertwaiveredfits.py#L156-L246 | [
"def",
"_processCommandLineArgs",
"(",
")",
":",
"import",
"getopt",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"\"hvmo:\"",
",",
"[",
"\"help\"",
",",
"\"verbose\"",
",",
"\"multiEx... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | _verify | Verify that the input HDUList is for a waivered FITS file.
Parameters:
waiveredHdul HDUList object to be verified
Returns: None
Exceptions:
ValueError Input HDUList is not for a waivered FITS file | lib/stsci/tools/convertwaiveredfits.py | def _verify(waiveredHdul):
"""
Verify that the input HDUList is for a waivered FITS file.
Parameters:
waiveredHdul HDUList object to be verified
Returns: None
Exceptions:
ValueError Input HDUList is not for a waivered FITS file
"""
if len... | def _verify(waiveredHdul):
"""
Verify that the input HDUList is for a waivered FITS file.
Parameters:
waiveredHdul HDUList object to be verified
Returns: None
Exceptions:
ValueError Input HDUList is not for a waivered FITS file
"""
if len... | [
"Verify",
"that",
"the",
"input",
"HDUList",
"is",
"for",
"a",
"waivered",
"FITS",
"file",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/convertwaiveredfits.py#L248-L288 | [
"def",
"_verify",
"(",
"waiveredHdul",
")",
":",
"if",
"len",
"(",
"waiveredHdul",
")",
"==",
"2",
":",
"#",
"# There must be exactly 2 HDU's",
"#",
"if",
"waiveredHdul",
"[",
"0",
"]",
".",
"header",
"[",
"'NAXIS'",
"]",
">",
"0",
":",
"#",
"# The Prima... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | toMultiExtensionFits | Convert the input waivered FITS object to a multi-extension FITS
HDUList object. Generate an output multi-extension FITS file if
requested.
Parameters:
waiveredObject input object representing a waivered FITS file;
either a astroyp.io.fits.HDUList object, ... | lib/stsci/tools/convertwaiveredfits.py | def toMultiExtensionFits(waiveredObject,
multiExtensionFileName=None,
forceFileOutput=False,
verbose=False):
"""
Convert the input waivered FITS object to a multi-extension FITS
HDUList object. Generate an output multi-exten... | def toMultiExtensionFits(waiveredObject,
multiExtensionFileName=None,
forceFileOutput=False,
verbose=False):
"""
Convert the input waivered FITS object to a multi-extension FITS
HDUList object. Generate an output multi-exten... | [
"Convert",
"the",
"input",
"waivered",
"FITS",
"object",
"to",
"a",
"multi",
"-",
"extension",
"FITS",
"HDUList",
"object",
".",
"Generate",
"an",
"output",
"multi",
"-",
"extension",
"FITS",
"file",
"if",
"requested",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/convertwaiveredfits.py#L290-L512 | [
"def",
"toMultiExtensionFits",
"(",
"waiveredObject",
",",
"multiExtensionFileName",
"=",
"None",
",",
"forceFileOutput",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"waiveredObject",
",",
"fits",
".",
"HDUList",
")",
":",
"w... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | convertwaiveredfits | Convert the input waivered FITS object to various formats. The
default conversion format is multi-extension FITS. Generate an output
file in the desired format if requested.
Parameters:
waiveredObject input object representing a waivered FITS file;
either... | lib/stsci/tools/convertwaiveredfits.py | def convertwaiveredfits(waiveredObject,
outputFileName=None,
forceFileOutput=False,
convertTo='multiExtension',
verbose=False):
"""
Convert the input waivered FITS object to various formats. The
default ... | def convertwaiveredfits(waiveredObject,
outputFileName=None,
forceFileOutput=False,
convertTo='multiExtension',
verbose=False):
"""
Convert the input waivered FITS object to various formats. The
default ... | [
"Convert",
"the",
"input",
"waivered",
"FITS",
"object",
"to",
"various",
"formats",
".",
"The",
"default",
"conversion",
"format",
"is",
"multi",
"-",
"extension",
"FITS",
".",
"Generate",
"an",
"output",
"file",
"in",
"the",
"desired",
"format",
"if",
"req... | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/convertwaiveredfits.py#L515-L563 | [
"def",
"convertwaiveredfits",
"(",
"waiveredObject",
",",
"outputFileName",
"=",
"None",
",",
"forceFileOutput",
"=",
"False",
",",
"convertTo",
"=",
"'multiExtension'",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"convertTo",
"==",
"'multiExtension'",
":",
"f... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | to_jd | Determine Julian day from Persian date | convertdate/persian.py | def to_jd(year, month, day):
'''Determine Julian day from Persian date'''
if year >= 0:
y = 474
else:
y = 473
epbase = year - y
epyear = 474 + (epbase % 2820)
if month <= 7:
m = (month - 1) * 31
else:
m = (month - 1) * 30 + 6
return day + m + trunc(((ep... | def to_jd(year, month, day):
'''Determine Julian day from Persian date'''
if year >= 0:
y = 474
else:
y = 473
epbase = year - y
epyear = 474 + (epbase % 2820)
if month <= 7:
m = (month - 1) * 31
else:
m = (month - 1) * 30 + 6
return day + m + trunc(((ep... | [
"Determine",
"Julian",
"day",
"from",
"Persian",
"date"
] | fitnr/convertdate | python | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/persian.py#L33-L48 | [
"def",
"to_jd",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"if",
"year",
">=",
"0",
":",
"y",
"=",
"474",
"else",
":",
"y",
"=",
"473",
"epbase",
"=",
"year",
"-",
"y",
"epyear",
"=",
"474",
"+",
"(",
"epbase",
"%",
"2820",
")",
"if",
... | e920f168a87f99183b0aa7290d6c3af222582d43 |
train | from_jd | Calculate Persian date from Julian day | convertdate/persian.py | def from_jd(jd):
'''Calculate Persian date from Julian day'''
jd = trunc(jd) + 0.5
depoch = jd - to_jd(475, 1, 1)
cycle = trunc(depoch / 1029983)
cyear = (depoch % 1029983)
if cyear == 1029982:
ycycle = 2820
else:
aux1 = trunc(cyear / 366)
aux2 = cyear % 366
... | def from_jd(jd):
'''Calculate Persian date from Julian day'''
jd = trunc(jd) + 0.5
depoch = jd - to_jd(475, 1, 1)
cycle = trunc(depoch / 1029983)
cyear = (depoch % 1029983)
if cyear == 1029982:
ycycle = 2820
else:
aux1 = trunc(cyear / 366)
aux2 = cyear % 366
... | [
"Calculate",
"Persian",
"date",
"from",
"Julian",
"day"
] | fitnr/convertdate | python | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/persian.py#L51-L80 | [
"def",
"from_jd",
"(",
"jd",
")",
":",
"jd",
"=",
"trunc",
"(",
"jd",
")",
"+",
"0.5",
"depoch",
"=",
"jd",
"-",
"to_jd",
"(",
"475",
",",
"1",
",",
"1",
")",
"cycle",
"=",
"trunc",
"(",
"depoch",
"/",
"1029983",
")",
"cyear",
"=",
"(",
"depo... | e920f168a87f99183b0aa7290d6c3af222582d43 |
train | setup_global_logging | Initializes capture of stdout/stderr, Python warnings, and exceptions;
redirecting them to the loggers for the modules from which they originated. | lib/stsci/tools/logutil.py | def setup_global_logging():
"""
Initializes capture of stdout/stderr, Python warnings, and exceptions;
redirecting them to the loggers for the modules from which they originated.
"""
global global_logging_started
if not PY3K:
sys.exc_clear()
if global_logging_started:
retu... | def setup_global_logging():
"""
Initializes capture of stdout/stderr, Python warnings, and exceptions;
redirecting them to the loggers for the modules from which they originated.
"""
global global_logging_started
if not PY3K:
sys.exc_clear()
if global_logging_started:
retu... | [
"Initializes",
"capture",
"of",
"stdout",
"/",
"stderr",
"Python",
"warnings",
"and",
"exceptions",
";",
"redirecting",
"them",
"to",
"the",
"loggers",
"for",
"the",
"modules",
"from",
"which",
"they",
"originated",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/logutil.py#L390-L428 | [
"def",
"setup_global_logging",
"(",
")",
":",
"global",
"global_logging_started",
"if",
"not",
"PY3K",
":",
"sys",
".",
"exc_clear",
"(",
")",
"if",
"global_logging_started",
":",
"return",
"orig_logger_class",
"=",
"logging",
".",
"getLoggerClass",
"(",
")",
"l... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | teardown_global_logging | Disable global logging of stdio, warnings, and exceptions. | lib/stsci/tools/logutil.py | def teardown_global_logging():
"""Disable global logging of stdio, warnings, and exceptions."""
global global_logging_started
if not global_logging_started:
return
stdout_logger = logging.getLogger(__name__ + '.stdout')
stderr_logger = logging.getLogger(__name__ + '.stderr')
if sys.std... | def teardown_global_logging():
"""Disable global logging of stdio, warnings, and exceptions."""
global global_logging_started
if not global_logging_started:
return
stdout_logger = logging.getLogger(__name__ + '.stdout')
stderr_logger = logging.getLogger(__name__ + '.stderr')
if sys.std... | [
"Disable",
"global",
"logging",
"of",
"stdio",
"warnings",
"and",
"exceptions",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/logutil.py#L431-L464 | [
"def",
"teardown_global_logging",
"(",
")",
":",
"global",
"global_logging_started",
"if",
"not",
"global_logging_started",
":",
"return",
"stdout_logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
"+",
"'.stdout'",
")",
"stderr_logger",
"=",
"logging",
"."... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | create_logger | Do basic configuration for the logging system. Similar to
logging.basicConfig but the logger ``name`` is configurable and both a file
output and a stream output can be created. Returns a logger object.
The default behaviour is to create a logger called ``name`` with a null
handled, and to use the "%(le... | lib/stsci/tools/logutil.py | def create_logger(name, format='%(levelname)s: %(message)s', datefmt=None,
stream=None, level=logging.INFO, filename=None, filemode='w',
filelevel=None, propagate=True):
"""
Do basic configuration for the logging system. Similar to
logging.basicConfig but the logger ``nam... | def create_logger(name, format='%(levelname)s: %(message)s', datefmt=None,
stream=None, level=logging.INFO, filename=None, filemode='w',
filelevel=None, propagate=True):
"""
Do basic configuration for the logging system. Similar to
logging.basicConfig but the logger ``nam... | [
"Do",
"basic",
"configuration",
"for",
"the",
"logging",
"system",
".",
"Similar",
"to",
"logging",
".",
"basicConfig",
"but",
"the",
"logger",
"name",
"is",
"configurable",
"and",
"both",
"a",
"file",
"output",
"and",
"a",
"stream",
"output",
"can",
"be",
... | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/logutil.py#L469-L527 | [
"def",
"create_logger",
"(",
"name",
",",
"format",
"=",
"'%(levelname)s: %(message)s'",
",",
"datefmt",
"=",
"None",
",",
"stream",
"=",
"None",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"filename",
"=",
"None",
",",
"filemode",
"=",
"'w'",
",",
"... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | StreamTeeLogger.set_stream | Set the stream that this logger is meant to replace. Usually this will
be either `sys.stdout` or `sys.stderr`, but can be any object with
`write()` and `flush()` methods, as supported by
`logging.StreamHandler`. | lib/stsci/tools/logutil.py | def set_stream(self, stream):
"""
Set the stream that this logger is meant to replace. Usually this will
be either `sys.stdout` or `sys.stderr`, but can be any object with
`write()` and `flush()` methods, as supported by
`logging.StreamHandler`.
"""
for handler ... | def set_stream(self, stream):
"""
Set the stream that this logger is meant to replace. Usually this will
be either `sys.stdout` or `sys.stderr`, but can be any object with
`write()` and `flush()` methods, as supported by
`logging.StreamHandler`.
"""
for handler ... | [
"Set",
"the",
"stream",
"that",
"this",
"logger",
"is",
"meant",
"to",
"replace",
".",
"Usually",
"this",
"will",
"be",
"either",
"sys",
".",
"stdout",
"or",
"sys",
".",
"stderr",
"but",
"can",
"be",
"any",
"object",
"with",
"write",
"()",
"and",
"flus... | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/logutil.py#L206-L224 | [
"def",
"set_stream",
"(",
"self",
",",
"stream",
")",
":",
"for",
"handler",
"in",
"self",
".",
"handlers",
"[",
":",
"]",
":",
"if",
"isinstance",
"(",
"handler",
",",
"logging",
".",
"StreamHandler",
")",
":",
"self",
".",
"handlers",
".",
"remove",
... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | StreamTeeLogger.write | Buffers each message until a newline is reached. Each complete line is
then published to the logging system through ``self.log()``. | lib/stsci/tools/logutil.py | def write(self, message):
"""
Buffers each message until a newline is reached. Each complete line is
then published to the logging system through ``self.log()``.
"""
self.__thread_local_ctx.write_count += 1
try:
if self.__thread_local_ctx.write_count > 1:
... | def write(self, message):
"""
Buffers each message until a newline is reached. Each complete line is
then published to the logging system through ``self.log()``.
"""
self.__thread_local_ctx.write_count += 1
try:
if self.__thread_local_ctx.write_count > 1:
... | [
"Buffers",
"each",
"message",
"until",
"a",
"newline",
"is",
"reached",
".",
"Each",
"complete",
"line",
"is",
"then",
"published",
"to",
"the",
"logging",
"system",
"through",
"self",
".",
"log",
"()",
"."
] | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/logutil.py#L226-L245 | [
"def",
"write",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"__thread_local_ctx",
".",
"write_count",
"+=",
"1",
"try",
":",
"if",
"self",
".",
"__thread_local_ctx",
".",
"write_count",
">",
"1",
":",
"return",
"# For each line in the buffer ending with ... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | StreamTeeLogger.find_actual_caller | Returns the full-qualified module name, full pathname, line number, and
function in which `StreamTeeLogger.write()` was called. For example,
if this instance is used to replace `sys.stdout`, this will return the
location of any print statement. | lib/stsci/tools/logutil.py | def find_actual_caller(self):
"""
Returns the full-qualified module name, full pathname, line number, and
function in which `StreamTeeLogger.write()` was called. For example,
if this instance is used to replace `sys.stdout`, this will return the
location of any print statement.
... | def find_actual_caller(self):
"""
Returns the full-qualified module name, full pathname, line number, and
function in which `StreamTeeLogger.write()` was called. For example,
if this instance is used to replace `sys.stdout`, this will return the
location of any print statement.
... | [
"Returns",
"the",
"full",
"-",
"qualified",
"module",
"name",
"full",
"pathname",
"line",
"number",
"and",
"function",
"in",
"which",
"StreamTeeLogger",
".",
"write",
"()",
"was",
"called",
".",
"For",
"example",
"if",
"this",
"instance",
"is",
"used",
"to",... | spacetelescope/stsci.tools | python | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/logutil.py#L274-L310 | [
"def",
"find_actual_caller",
"(",
"self",
")",
":",
"# Gleaned from code in the logging module itself...",
"try",
":",
"f",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
"##f = inspect.currentframe(1)",
"except",
"Exception",
":",
"f",
"=",
"None",
"# On some versions ... | 9a022503ad24ca54ce83331482dfa3ff6de9f403 |
train | load | Deserialize ``fp`` (a ``.read()``-supporting file-like object
containing a XPORT document) to a Python object. | xport/__init__.py | def load(fp):
'''
Deserialize ``fp`` (a ``.read()``-supporting file-like object
containing a XPORT document) to a Python object.
'''
reader = reading.Reader(fp)
keys = reader.fields
columns = {k: [] for k in keys}
for row in reader:
for key, value in zip(keys, row):
c... | def load(fp):
'''
Deserialize ``fp`` (a ``.read()``-supporting file-like object
containing a XPORT document) to a Python object.
'''
reader = reading.Reader(fp)
keys = reader.fields
columns = {k: [] for k in keys}
for row in reader:
for key, value in zip(keys, row):
c... | [
"Deserialize",
"fp",
"(",
"a",
".",
"read",
"()",
"-",
"supporting",
"file",
"-",
"like",
"object",
"containing",
"a",
"XPORT",
"document",
")",
"to",
"a",
"Python",
"object",
"."
] | selik/xport | python | https://github.com/selik/xport/blob/fafd15a24ccd102fc92d0c0123b9877a0c752182/xport/__init__.py#L23-L34 | [
"def",
"load",
"(",
"fp",
")",
":",
"reader",
"=",
"reading",
".",
"Reader",
"(",
"fp",
")",
"keys",
"=",
"reader",
".",
"fields",
"columns",
"=",
"{",
"k",
":",
"[",
"]",
"for",
"k",
"in",
"keys",
"}",
"for",
"row",
"in",
"reader",
":",
"for",... | fafd15a24ccd102fc92d0c0123b9877a0c752182 |
train | HydroQuebecClient._get_login_page | Go to the login page. | pyhydroquebec/client.py | def _get_login_page(self):
"""Go to the login page."""
try:
raw_res = yield from self._session.get(HOME_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can not connect to login page")
# Get l... | def _get_login_page(self):
"""Go to the login page."""
try:
raw_res = yield from self._session.get(HOME_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can not connect to login page")
# Get l... | [
"Go",
"to",
"the",
"login",
"page",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L73-L89 | [
"def",
"_get_login_page",
"(",
"self",
")",
":",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
"get",
"(",
"HOME_URL",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSError",
":",
"raise",
"PyHydroQuebecError",
... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient._post_login_page | Login to HydroQuebec website. | pyhydroquebec/client.py | def _post_login_page(self, login_url):
"""Login to HydroQuebec website."""
data = {"login": self.username,
"_58_password": self.password}
try:
raw_res = yield from self._session.post(login_url,
data=data,
... | def _post_login_page(self, login_url):
"""Login to HydroQuebec website."""
data = {"login": self.username,
"_58_password": self.password}
try:
raw_res = yield from self._session.post(login_url,
data=data,
... | [
"Login",
"to",
"HydroQuebec",
"website",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L92-L107 | [
"def",
"_post_login_page",
"(",
"self",
",",
"login_url",
")",
":",
"data",
"=",
"{",
"\"login\"",
":",
"self",
".",
"username",
",",
"\"_58_password\"",
":",
"self",
".",
"password",
"}",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_sessi... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient._get_p_p_id_and_contract | Get id of consumption profile. | pyhydroquebec/client.py | def _get_p_p_id_and_contract(self):
"""Get id of consumption profile."""
contracts = {}
try:
raw_res = yield from self._session.get(PROFILE_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can... | def _get_p_p_id_and_contract(self):
"""Get id of consumption profile."""
contracts = {}
try:
raw_res = yield from self._session.get(PROFILE_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can... | [
"Get",
"id",
"of",
"consumption",
"profile",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L110-L142 | [
"def",
"_get_p_p_id_and_contract",
"(",
"self",
")",
":",
"contracts",
"=",
"{",
"}",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
"get",
"(",
"PROFILE_URL",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSEr... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient._get_lonely_contract | Get contract number when we have only one contract. | pyhydroquebec/client.py | def _get_lonely_contract(self):
"""Get contract number when we have only one contract."""
contracts = {}
try:
raw_res = yield from self._session.get(MAIN_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQu... | def _get_lonely_contract(self):
"""Get contract number when we have only one contract."""
contracts = {}
try:
raw_res = yield from self._session.get(MAIN_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQu... | [
"Get",
"contract",
"number",
"when",
"we",
"have",
"only",
"one",
"contract",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L145-L166 | [
"def",
"_get_lonely_contract",
"(",
"self",
")",
":",
"contracts",
"=",
"{",
"}",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
"get",
"(",
"MAIN_URL",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSError",
... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient._get_balances | Get all balances.
.. todo::
IT SEEMS balances are shown (MAIN_URL) in the same order
that contracts in profile page (PROFILE_URL).
Maybe we should ensure that. | pyhydroquebec/client.py | def _get_balances(self):
"""Get all balances.
.. todo::
IT SEEMS balances are shown (MAIN_URL) in the same order
that contracts in profile page (PROFILE_URL).
Maybe we should ensure that.
"""
balances = []
try:
raw_res = yield fro... | def _get_balances(self):
"""Get all balances.
.. todo::
IT SEEMS balances are shown (MAIN_URL) in the same order
that contracts in profile page (PROFILE_URL).
Maybe we should ensure that.
"""
balances = []
try:
raw_res = yield fro... | [
"Get",
"all",
"balances",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L169-L199 | [
"def",
"_get_balances",
"(",
"self",
")",
":",
"balances",
"=",
"[",
"]",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
"get",
"(",
"MAIN_URL",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSError",
":",
... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient._load_contract_page | Load the profile page of a specific contract when we have multiple contracts. | pyhydroquebec/client.py | def _load_contract_page(self, contract_url):
"""Load the profile page of a specific contract when we have multiple contracts."""
try:
yield from self._session.get(contract_url,
timeout=self._timeout)
except OSError:
raise PyHydroQu... | def _load_contract_page(self, contract_url):
"""Load the profile page of a specific contract when we have multiple contracts."""
try:
yield from self._session.get(contract_url,
timeout=self._timeout)
except OSError:
raise PyHydroQu... | [
"Load",
"the",
"profile",
"page",
"of",
"a",
"specific",
"contract",
"when",
"we",
"have",
"multiple",
"contracts",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L202-L209 | [
"def",
"_load_contract_page",
"(",
"self",
",",
"contract_url",
")",
":",
"try",
":",
"yield",
"from",
"self",
".",
"_session",
".",
"get",
"(",
"contract_url",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSError",
":",
"raise",
"PyHydroQ... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient._get_annual_data | Get annual data. | pyhydroquebec/client.py | def _get_annual_data(self, p_p_id):
"""Get annual data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationAnnuelles"}
try:
... | def _get_annual_data(self, p_p_id):
"""Get annual data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationAnnuelles"}
try:
... | [
"Get",
"annual",
"data",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L212-L239 | [
"def",
"_get_annual_data",
"(",
"self",
",",
"p_p_id",
")",
":",
"params",
"=",
"{",
"\"p_p_id\"",
":",
"p_p_id",
",",
"\"p_p_lifecycle\"",
":",
"2",
",",
"\"p_p_state\"",
":",
"\"normal\"",
",",
"\"p_p_mode\"",
":",
"\"view\"",
",",
"\"p_p_resource_id\"",
":"... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient._get_monthly_data | Get monthly data. | pyhydroquebec/client.py | def _get_monthly_data(self, p_p_id):
"""Get monthly data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_resource_id": ("resourceObtenirDonnees"
"PeriodesConsommation")}
try:
raw_res = yield from self.... | def _get_monthly_data(self, p_p_id):
"""Get monthly data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_resource_id": ("resourceObtenirDonnees"
"PeriodesConsommation")}
try:
raw_res = yield from self.... | [
"Get",
"monthly",
"data",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L242-L262 | [
"def",
"_get_monthly_data",
"(",
"self",
",",
"p_p_id",
")",
":",
"params",
"=",
"{",
"\"p_p_id\"",
":",
"p_p_id",
",",
"\"p_p_lifecycle\"",
":",
"2",
",",
"\"p_p_resource_id\"",
":",
"(",
"\"resourceObtenirDonnees\"",
"\"PeriodesConsommation\"",
")",
"}",
"try",
... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient._get_hourly_data | Get Hourly Data. | pyhydroquebec/client.py | def _get_hourly_data(self, day_date, p_p_id):
"""Get Hourly Data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationHoraires",
... | def _get_hourly_data(self, day_date, p_p_id):
"""Get Hourly Data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationHoraires",
... | [
"Get",
"Hourly",
"Data",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L290-L355 | [
"def",
"_get_hourly_data",
"(",
"self",
",",
"day_date",
",",
"p_p_id",
")",
":",
"params",
"=",
"{",
"\"p_p_id\"",
":",
"p_p_id",
",",
"\"p_p_lifecycle\"",
":",
"2",
",",
"\"p_p_state\"",
":",
"\"normal\"",
",",
"\"p_p_mode\"",
":",
"\"view\"",
",",
"\"p_p_... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient.fetch_data_detailled_energy_use | Get detailled energy use from a specific contract. | pyhydroquebec/client.py | def fetch_data_detailled_energy_use(self, start_date=None, end_date=None):
"""Get detailled energy use from a specific contract."""
if start_date is None:
start_date = datetime.datetime.now(HQ_TIMEZONE) - datetime.timedelta(days=1)
if end_date is None:
end_date = datetime... | def fetch_data_detailled_energy_use(self, start_date=None, end_date=None):
"""Get detailled energy use from a specific contract."""
if start_date is None:
start_date = datetime.datetime.now(HQ_TIMEZONE) - datetime.timedelta(days=1)
if end_date is None:
end_date = datetime... | [
"Get",
"detailled",
"energy",
"use",
"from",
"a",
"specific",
"contract",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L358-L392 | [
"def",
"fetch_data_detailled_energy_use",
"(",
"self",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
")",
":",
"if",
"start_date",
"is",
"None",
":",
"start_date",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"HQ_TIMEZONE",
")",
"-",
... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient.fetch_data | Get the latest data from HydroQuebec. | pyhydroquebec/client.py | def fetch_data(self):
"""Get the latest data from HydroQuebec."""
# Get http session
yield from self._get_httpsession()
# Get login page
login_url = yield from self._get_login_page()
# Post login page
yield from self._post_login_page(login_url)
# Get p_p_i... | def fetch_data(self):
"""Get the latest data from HydroQuebec."""
# Get http session
yield from self._get_httpsession()
# Get login page
login_url = yield from self._get_login_page()
# Post login page
yield from self._post_login_page(login_url)
# Get p_p_i... | [
"Get",
"the",
"latest",
"data",
"from",
"HydroQuebec",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L395-L468 | [
"def",
"fetch_data",
"(",
"self",
")",
":",
"# Get http session",
"yield",
"from",
"self",
".",
"_get_httpsession",
"(",
")",
"# Get login page",
"login_url",
"=",
"yield",
"from",
"self",
".",
"_get_login_page",
"(",
")",
"# Post login page",
"yield",
"from",
"... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | HydroQuebecClient.get_data | Return collected data. | pyhydroquebec/client.py | def get_data(self, contract=None):
"""Return collected data."""
if contract is None:
return self._data
if contract in self._data.keys():
return {contract: self._data[contract]}
raise PyHydroQuebecError("Contract {} not found".format(contract)) | def get_data(self, contract=None):
"""Return collected data."""
if contract is None:
return self._data
if contract in self._data.keys():
return {contract: self._data[contract]}
raise PyHydroQuebecError("Contract {} not found".format(contract)) | [
"Return",
"collected",
"data",
"."
] | titilambert/pyhydroquebec | python | https://github.com/titilambert/pyhydroquebec/blob/4ea1374a63944413889c147d91961eda0605d4fd/pyhydroquebec/client.py#L470-L476 | [
"def",
"get_data",
"(",
"self",
",",
"contract",
"=",
"None",
")",
":",
"if",
"contract",
"is",
"None",
":",
"return",
"self",
".",
"_data",
"if",
"contract",
"in",
"self",
".",
"_data",
".",
"keys",
"(",
")",
":",
"return",
"{",
"contract",
":",
"... | 4ea1374a63944413889c147d91961eda0605d4fd |
train | Heartbeater.ping | Posts the current state of each device to the server and schedules the next call in n seconds.
:param serverURL:
:return: | backend/src/recorder/common/heartbeater.py | def ping(self):
"""
Posts the current state of each device to the server and schedules the next call in n seconds.
:param serverURL:
:return:
"""
from datetime import datetime
nextRun = datetime.utcnow().timestamp() + self.cfg.getPingInterval()
self.sendHe... | def ping(self):
"""
Posts the current state of each device to the server and schedules the next call in n seconds.
:param serverURL:
:return:
"""
from datetime import datetime
nextRun = datetime.utcnow().timestamp() + self.cfg.getPingInterval()
self.sendHe... | [
"Posts",
"the",
"current",
"state",
"of",
"each",
"device",
"to",
"the",
"server",
"and",
"schedules",
"the",
"next",
"call",
"in",
"n",
"seconds",
".",
":",
"param",
"serverURL",
":",
":",
"return",
":"
] | 3ll3d00d/vibe | python | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/recorder/common/heartbeater.py#L16-L25 | [
"def",
"ping",
"(",
"self",
")",
":",
"from",
"datetime",
"import",
"datetime",
"nextRun",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"timestamp",
"(",
")",
"+",
"self",
".",
"cfg",
".",
"getPingInterval",
"(",
")",
"self",
".",
"sendHeartbeat",
"(... | 124b029f13ac746723e92cb47e9cb56edd2e54b5 |
train | Heartbeater.sendHeartbeat | Posts the current state to the server.
:param serverURL: the URL to ping.
:return: | backend/src/recorder/common/heartbeater.py | def sendHeartbeat(self):
"""
Posts the current state to the server.
:param serverURL: the URL to ping.
:return:
"""
for name, md in self.cfg.recordingDevices.items():
try:
data = marshal(md, recordingDeviceFields)
data['serviceU... | def sendHeartbeat(self):
"""
Posts the current state to the server.
:param serverURL: the URL to ping.
:return:
"""
for name, md in self.cfg.recordingDevices.items():
try:
data = marshal(md, recordingDeviceFields)
data['serviceU... | [
"Posts",
"the",
"current",
"state",
"to",
"the",
"server",
".",
":",
"param",
"serverURL",
":",
"the",
"URL",
"to",
"ping",
".",
":",
"return",
":"
] | 3ll3d00d/vibe | python | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/recorder/common/heartbeater.py#L27-L46 | [
"def",
"sendHeartbeat",
"(",
"self",
")",
":",
"for",
"name",
",",
"md",
"in",
"self",
".",
"cfg",
".",
"recordingDevices",
".",
"items",
"(",
")",
":",
"try",
":",
"data",
"=",
"marshal",
"(",
"md",
",",
"recordingDeviceFields",
")",
"data",
"[",
"'... | 124b029f13ac746723e92cb47e9cb56edd2e54b5 |
train | Heartbeater.scheduleNextHeartbeat | Schedules the next ping.
:param nextRun: when we should run next.
:param serverURL: the URL to ping.
:return: | backend/src/recorder/common/heartbeater.py | def scheduleNextHeartbeat(self, nextRun):
"""
Schedules the next ping.
:param nextRun: when we should run next.
:param serverURL: the URL to ping.
:return:
"""
import threading
from datetime import datetime
tilNextTime = max(nextRun - datetime.utcn... | def scheduleNextHeartbeat(self, nextRun):
"""
Schedules the next ping.
:param nextRun: when we should run next.
:param serverURL: the URL to ping.
:return:
"""
import threading
from datetime import datetime
tilNextTime = max(nextRun - datetime.utcn... | [
"Schedules",
"the",
"next",
"ping",
".",
":",
"param",
"nextRun",
":",
"when",
"we",
"should",
"run",
"next",
".",
":",
"param",
"serverURL",
":",
"the",
"URL",
"to",
"ping",
".",
":",
"return",
":"
] | 3ll3d00d/vibe | python | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/recorder/common/heartbeater.py#L48-L59 | [
"def",
"scheduleNextHeartbeat",
"(",
"self",
",",
"nextRun",
")",
":",
"import",
"threading",
"from",
"datetime",
"import",
"datetime",
"tilNextTime",
"=",
"max",
"(",
"nextRun",
"-",
"datetime",
".",
"utcnow",
"(",
")",
".",
"timestamp",
"(",
")",
",",
"0... | 124b029f13ac746723e92cb47e9cb56edd2e54b5 |
train | CollectionMatcher._validate_argument | Validate a type or matcher argument to the constructor. | callee/collections.py | def _validate_argument(self, arg):
"""Validate a type or matcher argument to the constructor."""
if arg is None:
return arg
if isinstance(arg, type):
return InstanceOf(arg)
if not isinstance(arg, BaseMatcher):
raise TypeError(
"argumen... | def _validate_argument(self, arg):
"""Validate a type or matcher argument to the constructor."""
if arg is None:
return arg
if isinstance(arg, type):
return InstanceOf(arg)
if not isinstance(arg, BaseMatcher):
raise TypeError(
"argumen... | [
"Validate",
"a",
"type",
"or",
"matcher",
"argument",
"to",
"the",
"constructor",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/collections.py#L38-L50 | [
"def",
"_validate_argument",
"(",
"self",
",",
"arg",
")",
":",
"if",
"arg",
"is",
"None",
":",
"return",
"arg",
"if",
"isinstance",
"(",
"arg",
",",
"type",
")",
":",
"return",
"InstanceOf",
"(",
"arg",
")",
"if",
"not",
"isinstance",
"(",
"arg",
",... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | MappingMatcher._initialize | Initiaize the mapping matcher with constructor arguments. | callee/collections.py | def _initialize(self, *args, **kwargs):
"""Initiaize the mapping matcher with constructor arguments."""
self.items = None
self.keys = None
self.values = None
if args:
if len(args) != 2:
raise TypeError("expected exactly two positional arguments, "
... | def _initialize(self, *args, **kwargs):
"""Initiaize the mapping matcher with constructor arguments."""
self.items = None
self.keys = None
self.values = None
if args:
if len(args) != 2:
raise TypeError("expected exactly two positional arguments, "
... | [
"Initiaize",
"the",
"mapping",
"matcher",
"with",
"constructor",
"arguments",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/collections.py#L163-L208 | [
"def",
"_initialize",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"items",
"=",
"None",
"self",
".",
"keys",
"=",
"None",
"self",
".",
"values",
"=",
"None",
"if",
"args",
":",
"if",
"len",
"(",
"args",
")",
"... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | docs | Build the docs and show them in default web browser. | tasks.py | def docs(ctx, output='html', rebuild=False, show=True, verbose=True):
"""Build the docs and show them in default web browser."""
sphinx_build = ctx.run(
'sphinx-build -b {output} {all} {verbose} docs docs/_build'.format(
output=output,
all='-a -E' if rebuild else '',
... | def docs(ctx, output='html', rebuild=False, show=True, verbose=True):
"""Build the docs and show them in default web browser."""
sphinx_build = ctx.run(
'sphinx-build -b {output} {all} {verbose} docs docs/_build'.format(
output=output,
all='-a -E' if rebuild else '',
... | [
"Build",
"the",
"docs",
"and",
"show",
"them",
"in",
"default",
"web",
"browser",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/tasks.py#L47-L61 | [
"def",
"docs",
"(",
"ctx",
",",
"output",
"=",
"'html'",
",",
"rebuild",
"=",
"False",
",",
"show",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"sphinx_build",
"=",
"ctx",
".",
"run",
"(",
"'sphinx-build -b {output} {all} {verbose} docs docs/_build'",
... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | upload | Upload the package to PyPI. | tasks.py | def upload(ctx, yes=False):
"""Upload the package to PyPI."""
import callee
version = callee.__version__
# check the packages version
# TODO: add a 'release' to automatically bless a version as release one
if version.endswith('-dev'):
fatal("Can't upload a development version (%s) to Py... | def upload(ctx, yes=False):
"""Upload the package to PyPI."""
import callee
version = callee.__version__
# check the packages version
# TODO: add a 'release' to automatically bless a version as release one
if version.endswith('-dev'):
fatal("Can't upload a development version (%s) to Py... | [
"Upload",
"the",
"package",
"to",
"PyPI",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/tasks.py#L69-L101 | [
"def",
"upload",
"(",
"ctx",
",",
"yes",
"=",
"False",
")",
":",
"import",
"callee",
"version",
"=",
"callee",
".",
"__version__",
"# check the packages version",
"# TODO: add a 'release' to automatically bless a version as release one",
"if",
"version",
".",
"endswith",
... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | fatal | Log an error message and exit.
Following arguments are keyword-only.
:param exitcode: Optional exit code to use
:param cause: Optional Invoke's Result object, i.e.
result of a subprocess invocation | tasks.py | def fatal(*args, **kwargs):
"""Log an error message and exit.
Following arguments are keyword-only.
:param exitcode: Optional exit code to use
:param cause: Optional Invoke's Result object, i.e.
result of a subprocess invocation
"""
# determine the exitcode to return to the o... | def fatal(*args, **kwargs):
"""Log an error message and exit.
Following arguments are keyword-only.
:param exitcode: Optional exit code to use
:param cause: Optional Invoke's Result object, i.e.
result of a subprocess invocation
"""
# determine the exitcode to return to the o... | [
"Log",
"an",
"error",
"message",
"and",
"exit",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/tasks.py#L106-L128 | [
"def",
"fatal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# determine the exitcode to return to the operating system",
"exitcode",
"=",
"None",
"if",
"'exitcode'",
"in",
"kwargs",
":",
"exitcode",
"=",
"kwargs",
".",
"pop",
"(",
"'exitcode'",
")",
... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | rungtd1d | This is the "atomic" function looped by other functions | archive/f2py.py | def rungtd1d(time: Union[datetime, str, np.ndarray],
altkm: np.ndarray,
glat: float, glon: float) -> xarray.Dataset:
"""
This is the "atomic" function looped by other functions
"""
time = todt64(time)
# %% get solar parameters for date
f107Ap = gi.getApF107(time, smooth... | def rungtd1d(time: Union[datetime, str, np.ndarray],
altkm: np.ndarray,
glat: float, glon: float) -> xarray.Dataset:
"""
This is the "atomic" function looped by other functions
"""
time = todt64(time)
# %% get solar parameters for date
f107Ap = gi.getApF107(time, smooth... | [
"This",
"is",
"the",
"atomic",
"function",
"looped",
"by",
"other",
"functions"
] | scivision/msise00 | python | https://github.com/scivision/msise00/blob/13a283ec02679ab74672f284ba68a7a8f896dc6f/archive/f2py.py#L3-L51 | [
"def",
"rungtd1d",
"(",
"time",
":",
"Union",
"[",
"datetime",
",",
"str",
",",
"np",
".",
"ndarray",
"]",
",",
"altkm",
":",
"np",
".",
"ndarray",
",",
"glat",
":",
"float",
",",
"glon",
":",
"float",
")",
"->",
"xarray",
".",
"Dataset",
":",
"t... | 13a283ec02679ab74672f284ba68a7a8f896dc6f |
train | SubscriptionView.form_valid | Call `form.save()` and super itself. | mailjet/contrib/django_mailjet/views.py | def form_valid(self, form):
""" Call `form.save()` and super itself. """
form.save()
return super(SubscriptionView, self).form_valid(form) | def form_valid(self, form):
""" Call `form.save()` and super itself. """
form.save()
return super(SubscriptionView, self).form_valid(form) | [
"Call",
"form",
".",
"save",
"()",
"and",
"super",
"itself",
"."
] | WoLpH/mailjet | python | https://github.com/WoLpH/mailjet/blob/f7f5102bf52be6a4a9c62afe474387481c806e27/mailjet/contrib/django_mailjet/views.py#L13-L16 | [
"def",
"form_valid",
"(",
"self",
",",
"form",
")",
":",
"form",
".",
"save",
"(",
")",
"return",
"super",
"(",
"SubscriptionView",
",",
"self",
")",
".",
"form_valid",
"(",
"form",
")"
] | f7f5102bf52be6a4a9c62afe474387481c806e27 |
train | AsyncOWAPI._uses_aiohttp_session | This is a decorator that creates an async with statement around a function, and makes sure that a _session argument is always passed.
Only usable on async functions of course.
The _session argument is (supposed to be) an aiohttp.ClientSession instance in all functions that this decorator has been used o... | overwatch_api/core.py | def _uses_aiohttp_session(func):
"""This is a decorator that creates an async with statement around a function, and makes sure that a _session argument is always passed.
Only usable on async functions of course.
The _session argument is (supposed to be) an aiohttp.ClientSession instance in all f... | def _uses_aiohttp_session(func):
"""This is a decorator that creates an async with statement around a function, and makes sure that a _session argument is always passed.
Only usable on async functions of course.
The _session argument is (supposed to be) an aiohttp.ClientSession instance in all f... | [
"This",
"is",
"a",
"decorator",
"that",
"creates",
"an",
"async",
"with",
"statement",
"around",
"a",
"function",
"and",
"makes",
"sure",
"that",
"a",
"_session",
"argument",
"is",
"always",
"passed",
".",
"Only",
"usable",
"on",
"async",
"functions",
"of",
... | anthok/overwatch-api | python | https://github.com/anthok/overwatch-api/blob/aba976a3c07c4932de13f4236d924b2901b149b9/overwatch_api/core.py#L46-L64 | [
"def",
"_uses_aiohttp_session",
"(",
"func",
")",
":",
"# The function the decorator returns",
"async",
"def",
"decorated_func",
"(",
"*",
"args",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"session",
"is",
"not",
"None",
":",
"# T... | aba976a3c07c4932de13f4236d924b2901b149b9 |
train | AsyncOWAPI._add_request_parameters | Adds the ratelimit and request timeout parameters to a function. | overwatch_api/core.py | def _add_request_parameters(func):
"""Adds the ratelimit and request timeout parameters to a function."""
# The function the decorator returns
async def decorated_func(*args, handle_ratelimit=None, max_tries=None, request_timeout=None, **kwargs):
return await func(*args, handle_rate... | def _add_request_parameters(func):
"""Adds the ratelimit and request timeout parameters to a function."""
# The function the decorator returns
async def decorated_func(*args, handle_ratelimit=None, max_tries=None, request_timeout=None, **kwargs):
return await func(*args, handle_rate... | [
"Adds",
"the",
"ratelimit",
"and",
"request",
"timeout",
"parameters",
"to",
"a",
"function",
"."
] | anthok/overwatch-api | python | https://github.com/anthok/overwatch-api/blob/aba976a3c07c4932de13f4236d924b2901b149b9/overwatch_api/core.py#L66-L75 | [
"def",
"_add_request_parameters",
"(",
"func",
")",
":",
"# The function the decorator returns",
"async",
"def",
"decorated_func",
"(",
"*",
"args",
",",
"handle_ratelimit",
"=",
"None",
",",
"max_tries",
"=",
"None",
",",
"request_timeout",
"=",
"None",
",",
"*",... | aba976a3c07c4932de13f4236d924b2901b149b9 |
train | AsyncOWAPI.get_stats | Returns the stats for the profiles on the specified regions and platform. The format for regions without a matching user, the format is the same as get_profile.
The stats are returned in a dictionary with a similar format to what https://github.com/SunDwarf/OWAPI/blob/master/api.md#get-apiv3ubattletagstats spec... | overwatch_api/core.py | async def get_stats(self, battletag: str, regions=(EUROPE, KOREA, AMERICAS, CHINA, JAPAN, ANY),
platform=None, _session=None, handle_ratelimit=None, max_tries=None, request_timeout=None):
"""Returns the stats for the profiles on the specified regions and platform. The format for regions ... | async def get_stats(self, battletag: str, regions=(EUROPE, KOREA, AMERICAS, CHINA, JAPAN, ANY),
platform=None, _session=None, handle_ratelimit=None, max_tries=None, request_timeout=None):
"""Returns the stats for the profiles on the specified regions and platform. The format for regions ... | [
"Returns",
"the",
"stats",
"for",
"the",
"profiles",
"on",
"the",
"specified",
"regions",
"and",
"platform",
".",
"The",
"format",
"for",
"regions",
"without",
"a",
"matching",
"user",
"the",
"format",
"is",
"the",
"same",
"as",
"get_profile",
".",
"The",
... | anthok/overwatch-api | python | https://github.com/anthok/overwatch-api/blob/aba976a3c07c4932de13f4236d924b2901b149b9/overwatch_api/core.py#L98-L114 | [
"async",
"def",
"get_stats",
"(",
"self",
",",
"battletag",
":",
"str",
",",
"regions",
"=",
"(",
"EUROPE",
",",
"KOREA",
",",
"AMERICAS",
",",
"CHINA",
",",
"JAPAN",
",",
"ANY",
")",
",",
"platform",
"=",
"None",
",",
"_session",
"=",
"None",
",",
... | aba976a3c07c4932de13f4236d924b2901b149b9 |
train | AsyncOWAPI._base_request | Does a request to some endpoint. This is also where ratelimit logic is handled. | overwatch_api/core.py | async def _base_request(self, battle_tag: str, endpoint_name: str, session: aiohttp.ClientSession, *, platform=None,
handle_ratelimit=None, max_tries=None, request_timeout=None):
"""Does a request to some endpoint. This is also where ratelimit logic is handled."""
# We check ... | async def _base_request(self, battle_tag: str, endpoint_name: str, session: aiohttp.ClientSession, *, platform=None,
handle_ratelimit=None, max_tries=None, request_timeout=None):
"""Does a request to some endpoint. This is also where ratelimit logic is handled."""
# We check ... | [
"Does",
"a",
"request",
"to",
"some",
"endpoint",
".",
"This",
"is",
"also",
"where",
"ratelimit",
"logic",
"is",
"handled",
"."
] | anthok/overwatch-api | python | https://github.com/anthok/overwatch-api/blob/aba976a3c07c4932de13f4236d924b2901b149b9/overwatch_api/core.py#L164-L224 | [
"async",
"def",
"_base_request",
"(",
"self",
",",
"battle_tag",
":",
"str",
",",
"endpoint_name",
":",
"str",
",",
"session",
":",
"aiohttp",
".",
"ClientSession",
",",
"*",
",",
"platform",
"=",
"None",
",",
"handle_ratelimit",
"=",
"None",
",",
"max_tri... | aba976a3c07c4932de13f4236d924b2901b149b9 |
train | AsyncOWAPI._async_get | Uses aiohttp to make a get request asynchronously.
Will raise asyncio.TimeoutError if the request could not be completed
within _async_timeout_seconds (default 5) seconds. | overwatch_api/core.py | async def _async_get(self, session: aiohttp.ClientSession, *args, _async_timeout_seconds: int = 5,
**kwargs):
"""Uses aiohttp to make a get request asynchronously.
Will raise asyncio.TimeoutError if the request could not be completed
within _async_timeout_seconds (defa... | async def _async_get(self, session: aiohttp.ClientSession, *args, _async_timeout_seconds: int = 5,
**kwargs):
"""Uses aiohttp to make a get request asynchronously.
Will raise asyncio.TimeoutError if the request could not be completed
within _async_timeout_seconds (defa... | [
"Uses",
"aiohttp",
"to",
"make",
"a",
"get",
"request",
"asynchronously",
".",
"Will",
"raise",
"asyncio",
".",
"TimeoutError",
"if",
"the",
"request",
"could",
"not",
"be",
"completed",
"within",
"_async_timeout_seconds",
"(",
"default",
"5",
")",
"seconds",
... | anthok/overwatch-api | python | https://github.com/anthok/overwatch-api/blob/aba976a3c07c4932de13f4236d924b2901b149b9/overwatch_api/core.py#L226-L235 | [
"async",
"def",
"_async_get",
"(",
"self",
",",
"session",
":",
"aiohttp",
".",
"ClientSession",
",",
"*",
"args",
",",
"_async_timeout_seconds",
":",
"int",
"=",
"5",
",",
"*",
"*",
"kwargs",
")",
":",
"# Taken almost directly from the aiohttp tutorial",
"with"... | aba976a3c07c4932de13f4236d924b2901b149b9 |
train | is_method | Check if argument is a method.
Optionally, we can also check if minimum or maximum arities
(number of accepted arguments) match given minimum and/or maximum. | callee/objects.py | def is_method(arg, min_arity=None, max_arity=None):
"""Check if argument is a method.
Optionally, we can also check if minimum or maximum arities
(number of accepted arguments) match given minimum and/or maximum.
"""
if not callable(arg):
return False
if not any(is_(arg) for is_ in (in... | def is_method(arg, min_arity=None, max_arity=None):
"""Check if argument is a method.
Optionally, we can also check if minimum or maximum arities
(number of accepted arguments) match given minimum and/or maximum.
"""
if not callable(arg):
return False
if not any(is_(arg) for is_ in (in... | [
"Check",
"if",
"argument",
"is",
"a",
"method",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/objects.py#L115-L154 | [
"def",
"is_method",
"(",
"arg",
",",
"min_arity",
"=",
"None",
",",
"max_arity",
"=",
"None",
")",
":",
"if",
"not",
"callable",
"(",
"arg",
")",
":",
"return",
"False",
"if",
"not",
"any",
"(",
"is_",
"(",
"arg",
")",
"for",
"is_",
"in",
"(",
"i... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | FileLike._is_readable | Check if the argument is a readable file-like object. | callee/objects.py | def _is_readable(self, obj):
"""Check if the argument is a readable file-like object."""
try:
read = getattr(obj, 'read')
except AttributeError:
return False
else:
return is_method(read, max_arity=1) | def _is_readable(self, obj):
"""Check if the argument is a readable file-like object."""
try:
read = getattr(obj, 'read')
except AttributeError:
return False
else:
return is_method(read, max_arity=1) | [
"Check",
"if",
"the",
"argument",
"is",
"a",
"readable",
"file",
"-",
"like",
"object",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/objects.py#L85-L92 | [
"def",
"_is_readable",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"read",
"=",
"getattr",
"(",
"obj",
",",
"'read'",
")",
"except",
"AttributeError",
":",
"return",
"False",
"else",
":",
"return",
"is_method",
"(",
"read",
",",
"max_arity",
"=",
"1... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | FileLike._is_writable | Check if the argument is a writable file-like object. | callee/objects.py | def _is_writable(self, obj):
"""Check if the argument is a writable file-like object."""
try:
write = getattr(obj, 'write')
except AttributeError:
return False
else:
return is_method(write, min_arity=1, max_arity=1) | def _is_writable(self, obj):
"""Check if the argument is a writable file-like object."""
try:
write = getattr(obj, 'write')
except AttributeError:
return False
else:
return is_method(write, min_arity=1, max_arity=1) | [
"Check",
"if",
"the",
"argument",
"is",
"a",
"writable",
"file",
"-",
"like",
"object",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/objects.py#L94-L101 | [
"def",
"_is_writable",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"write",
"=",
"getattr",
"(",
"obj",
",",
"'write'",
")",
"except",
"AttributeError",
":",
"return",
"False",
"else",
":",
"return",
"is_method",
"(",
"write",
",",
"min_arity",
"=",
... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | run | loops the rungtd1d function below. Figure it's easier to troubleshoot in Python than Fortran. | msise00/base.py | def run(time: datetime, altkm: float,
glat: Union[float, np.ndarray], glon: Union[float, np.ndarray], *,
f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
"""
loops the rungtd1d function below. Figure it's easier to troubleshoot in Python than Fortran.
"""
glat ... | def run(time: datetime, altkm: float,
glat: Union[float, np.ndarray], glon: Union[float, np.ndarray], *,
f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
"""
loops the rungtd1d function below. Figure it's easier to troubleshoot in Python than Fortran.
"""
glat ... | [
"loops",
"the",
"rungtd1d",
"function",
"below",
".",
"Figure",
"it",
"s",
"easier",
"to",
"troubleshoot",
"in",
"Python",
"than",
"Fortran",
"."
] | scivision/msise00 | python | https://github.com/scivision/msise00/blob/13a283ec02679ab74672f284ba68a7a8f896dc6f/msise00/base.py#L34-L51 | [
"def",
"run",
"(",
"time",
":",
"datetime",
",",
"altkm",
":",
"float",
",",
"glat",
":",
"Union",
"[",
"float",
",",
"np",
".",
"ndarray",
"]",
",",
"glon",
":",
"Union",
"[",
"float",
",",
"np",
".",
"ndarray",
"]",
",",
"*",
",",
"f107a",
":... | 13a283ec02679ab74672f284ba68a7a8f896dc6f |
train | loopalt_gtd | loop over location and time
time: datetime or numpy.datetime64 or list of datetime or np.ndarray of datetime
glat: float or 2-D np.ndarray
glon: float or 2-D np.ndarray
altkm: float or list or 1-D np.ndarray | msise00/base.py | def loopalt_gtd(time: datetime,
glat: Union[float, np.ndarray], glon: Union[float, np.ndarray],
altkm: Union[float, List[float], np.ndarray], *,
f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
"""
loop over location and time
time: ... | def loopalt_gtd(time: datetime,
glat: Union[float, np.ndarray], glon: Union[float, np.ndarray],
altkm: Union[float, List[float], np.ndarray], *,
f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
"""
loop over location and time
time: ... | [
"loop",
"over",
"location",
"and",
"time"
] | scivision/msise00 | python | https://github.com/scivision/msise00/blob/13a283ec02679ab74672f284ba68a7a8f896dc6f/msise00/base.py#L54-L87 | [
"def",
"loopalt_gtd",
"(",
"time",
":",
"datetime",
",",
"glat",
":",
"Union",
"[",
"float",
",",
"np",
".",
"ndarray",
"]",
",",
"glon",
":",
"Union",
"[",
"float",
",",
"np",
".",
"ndarray",
"]",
",",
"altkm",
":",
"Union",
"[",
"float",
",",
"... | 13a283ec02679ab74672f284ba68a7a8f896dc6f |
train | rungtd1d | This is the "atomic" function looped by other functions | msise00/base.py | def rungtd1d(time: datetime,
altkm: np.ndarray,
glat: float, glon: float, *,
f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
"""
This is the "atomic" function looped by other functions
"""
time = todatetime(time)
# %% get solar param... | def rungtd1d(time: datetime,
altkm: np.ndarray,
glat: float, glon: float, *,
f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
"""
This is the "atomic" function looped by other functions
"""
time = todatetime(time)
# %% get solar param... | [
"This",
"is",
"the",
"atomic",
"function",
"looped",
"by",
"other",
"functions"
] | scivision/msise00 | python | https://github.com/scivision/msise00/blob/13a283ec02679ab74672f284ba68a7a8f896dc6f/msise00/base.py#L90-L140 | [
"def",
"rungtd1d",
"(",
"time",
":",
"datetime",
",",
"altkm",
":",
"np",
".",
"ndarray",
",",
"glat",
":",
"float",
",",
"glon",
":",
"float",
",",
"*",
",",
"f107a",
":",
"float",
"=",
"None",
",",
"f107",
":",
"float",
"=",
"None",
",",
"Ap",
... | 13a283ec02679ab74672f284ba68a7a8f896dc6f |
train | Matching._validate_desc | Validate the predicate description. | callee/general.py | def _validate_desc(self, desc):
"""Validate the predicate description."""
if desc is None:
return desc
if not isinstance(desc, STRING_TYPES):
raise TypeError(
"predicate description for Matching must be a string, "
"got %r" % (type(desc),)... | def _validate_desc(self, desc):
"""Validate the predicate description."""
if desc is None:
return desc
if not isinstance(desc, STRING_TYPES):
raise TypeError(
"predicate description for Matching must be a string, "
"got %r" % (type(desc),)... | [
"Validate",
"the",
"predicate",
"description",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/general.py#L54-L74 | [
"def",
"_validate_desc",
"(",
"self",
",",
"desc",
")",
":",
"if",
"desc",
"is",
"None",
":",
"return",
"desc",
"if",
"not",
"isinstance",
"(",
"desc",
",",
"STRING_TYPES",
")",
":",
"raise",
"TypeError",
"(",
"\"predicate description for Matching must be a stri... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | OperatorMatcher._get_placeholder_repr | Return the placeholder part of matcher's ``__repr__``. | callee/operators.py | def _get_placeholder_repr(self):
"""Return the placeholder part of matcher's ``__repr__``."""
placeholder = '...'
if self.TRANSFORM is not None:
placeholder = '%s(%s)' % (self.TRANSFORM.__name__, placeholder)
return placeholder | def _get_placeholder_repr(self):
"""Return the placeholder part of matcher's ``__repr__``."""
placeholder = '...'
if self.TRANSFORM is not None:
placeholder = '%s(%s)' % (self.TRANSFORM.__name__, placeholder)
return placeholder | [
"Return",
"the",
"placeholder",
"part",
"of",
"matcher",
"s",
"__repr__",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/operators.py#L104-L109 | [
"def",
"_get_placeholder_repr",
"(",
"self",
")",
":",
"placeholder",
"=",
"'...'",
"if",
"self",
".",
"TRANSFORM",
"is",
"not",
"None",
":",
"placeholder",
"=",
"'%s(%s)'",
"%",
"(",
"self",
".",
"TRANSFORM",
".",
"__name__",
",",
"placeholder",
")",
"ret... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | BaseMatcherMetaclass._validate_class_definition | Ensure the matcher class definition is acceptable.
:raise RuntimeError: If there is a problem | callee/base.py | def _validate_class_definition(meta, classname, bases, dict_):
"""Ensure the matcher class definition is acceptable.
:raise RuntimeError: If there is a problem
"""
# let the BaseMatcher class be created without hassle
if meta._is_base_matcher_class_definition(classname, dict_):
... | def _validate_class_definition(meta, classname, bases, dict_):
"""Ensure the matcher class definition is acceptable.
:raise RuntimeError: If there is a problem
"""
# let the BaseMatcher class be created without hassle
if meta._is_base_matcher_class_definition(classname, dict_):
... | [
"Ensure",
"the",
"matcher",
"class",
"definition",
"is",
"acceptable",
".",
":",
"raise",
"RuntimeError",
":",
"If",
"there",
"is",
"a",
"problem"
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/base.py#L38-L71 | [
"def",
"_validate_class_definition",
"(",
"meta",
",",
"classname",
",",
"bases",
",",
"dict_",
")",
":",
"# let the BaseMatcher class be created without hassle",
"if",
"meta",
".",
"_is_base_matcher_class_definition",
"(",
"classname",
",",
"dict_",
")",
":",
"return",... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | BaseMatcherMetaclass._is_base_matcher_class_definition | Checks whether given class name and dictionary
define the :class:`BaseMatcher`. | callee/base.py | def _is_base_matcher_class_definition(meta, classname, dict_):
"""Checks whether given class name and dictionary
define the :class:`BaseMatcher`.
"""
if classname != 'BaseMatcher':
return False
methods = list(filter(inspect.isfunction, dict_.values()))
return ... | def _is_base_matcher_class_definition(meta, classname, dict_):
"""Checks whether given class name and dictionary
define the :class:`BaseMatcher`.
"""
if classname != 'BaseMatcher':
return False
methods = list(filter(inspect.isfunction, dict_.values()))
return ... | [
"Checks",
"whether",
"given",
"class",
"name",
"and",
"dictionary",
"define",
"the",
":",
"class",
":",
"BaseMatcher",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/base.py#L74-L81 | [
"def",
"_is_base_matcher_class_definition",
"(",
"meta",
",",
"classname",
",",
"dict_",
")",
":",
"if",
"classname",
"!=",
"'BaseMatcher'",
":",
"return",
"False",
"methods",
"=",
"list",
"(",
"filter",
"(",
"inspect",
".",
"isfunction",
",",
"dict_",
".",
... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | BaseMatcherMetaclass._list_magic_methods | Return names of magic methods defined by a class.
:return: Iterable of magic methods, each w/o the ``__`` prefix/suffix | callee/base.py | def _list_magic_methods(meta, class_):
"""Return names of magic methods defined by a class.
:return: Iterable of magic methods, each w/o the ``__`` prefix/suffix
"""
return [
name[2:-2] for name, member in class_.__dict__.items()
if len(name) > 4 and name.startswi... | def _list_magic_methods(meta, class_):
"""Return names of magic methods defined by a class.
:return: Iterable of magic methods, each w/o the ``__`` prefix/suffix
"""
return [
name[2:-2] for name, member in class_.__dict__.items()
if len(name) > 4 and name.startswi... | [
"Return",
"names",
"of",
"magic",
"methods",
"defined",
"by",
"a",
"class",
".",
":",
"return",
":",
"Iterable",
"of",
"magic",
"methods",
"each",
"w",
"/",
"o",
"the",
"__",
"prefix",
"/",
"suffix"
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/base.py#L84-L92 | [
"def",
"_list_magic_methods",
"(",
"meta",
",",
"class_",
")",
":",
"return",
"[",
"name",
"[",
"2",
":",
"-",
"2",
"]",
"for",
"name",
",",
"member",
"in",
"class_",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"len",
"(",
"name",
")",
">",
"4... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | semver | if (!(this instanceof SemVer))
return new SemVer(version, loose); | semver/__init__.py | def semver(version, loose):
if isinstance(version, SemVer):
if version.loose == loose:
return version
else:
version = version.version
elif not isinstance(version, str): # xxx:
raise InvalidTypeIncluded("must be str, but {!r}".format(version))
"""
if (!(t... | def semver(version, loose):
if isinstance(version, SemVer):
if version.loose == loose:
return version
else:
version = version.version
elif not isinstance(version, str): # xxx:
raise InvalidTypeIncluded("must be str, but {!r}".format(version))
"""
if (!(t... | [
"if",
"(",
"!",
"(",
"this",
"instanceof",
"SemVer",
"))",
"return",
"new",
"SemVer",
"(",
"version",
"loose",
")",
";"
] | podhmo/python-semver | python | https://github.com/podhmo/python-semver/blob/46d81c5d70ee716c48c7a8d44f9fefc6b86be33c/semver/__init__.py#L288-L301 | [
"def",
"semver",
"(",
"version",
",",
"loose",
")",
":",
"if",
"isinstance",
"(",
"version",
",",
"SemVer",
")",
":",
"if",
"version",
".",
"loose",
"==",
"loose",
":",
"return",
"version",
"else",
":",
"version",
"=",
"version",
".",
"version",
"elif"... | 46d81c5d70ee716c48c7a8d44f9fefc6b86be33c |
train | autodoc_process_docstring | Handler for the event emitted when autodoc processes a docstring.
See http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-docstring.
The TL;DR is that we can modify ``lines`` in-place to influence the output. | docs/conf.py | def autodoc_process_docstring(app, what, name, obj, options, lines):
"""Handler for the event emitted when autodoc processes a docstring.
See http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-docstring.
The TL;DR is that we can modify ``lines`` in-place to influence the output.
"""
# che... | def autodoc_process_docstring(app, what, name, obj, options, lines):
"""Handler for the event emitted when autodoc processes a docstring.
See http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-docstring.
The TL;DR is that we can modify ``lines`` in-place to influence the output.
"""
# che... | [
"Handler",
"for",
"the",
"event",
"emitted",
"when",
"autodoc",
"processes",
"a",
"docstring",
".",
"See",
"http",
":",
"//",
"sphinx",
"-",
"doc",
".",
"org",
"/",
"ext",
"/",
"autodoc",
".",
"html#event",
"-",
"autodoc",
"-",
"process",
"-",
"docstring... | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/docs/conf.py#L352-L374 | [
"def",
"autodoc_process_docstring",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"# check that only symbols that can be directly imported from ``callee``",
"# package are being documented",
"_",
",",
"symbol",
"=",
"name",
".... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | SubscriptionForm.clean_email | Raise ValidationError if the contact exists. | mailjet/contrib/django_mailjet/forms.py | def clean_email(self):
""" Raise ValidationError if the contact exists. """
contacts = self.api.lists.contacts(id=self.list_id)['result']
for contact in contacts:
if contact['email'] == self.cleaned_data['email']:
raise forms.ValidationError(
_(u'... | def clean_email(self):
""" Raise ValidationError if the contact exists. """
contacts = self.api.lists.contacts(id=self.list_id)['result']
for contact in contacts:
if contact['email'] == self.cleaned_data['email']:
raise forms.ValidationError(
_(u'... | [
"Raise",
"ValidationError",
"if",
"the",
"contact",
"exists",
"."
] | WoLpH/mailjet | python | https://github.com/WoLpH/mailjet/blob/f7f5102bf52be6a4a9c62afe474387481c806e27/mailjet/contrib/django_mailjet/forms.py#L23-L32 | [
"def",
"clean_email",
"(",
"self",
")",
":",
"contacts",
"=",
"self",
".",
"api",
".",
"lists",
".",
"contacts",
"(",
"id",
"=",
"self",
".",
"list_id",
")",
"[",
"'result'",
"]",
"for",
"contact",
"in",
"contacts",
":",
"if",
"contact",
"[",
"'email... | f7f5102bf52be6a4a9c62afe474387481c806e27 |
train | SubscriptionForm.add_contact | Create a contact with using the email on the list. | mailjet/contrib/django_mailjet/forms.py | def add_contact(self):
""" Create a contact with using the email on the list. """
self.api.lists.addcontact(
contact=self.cleaned_data['email'], id=self.list_id, method='POST') | def add_contact(self):
""" Create a contact with using the email on the list. """
self.api.lists.addcontact(
contact=self.cleaned_data['email'], id=self.list_id, method='POST') | [
"Create",
"a",
"contact",
"with",
"using",
"the",
"email",
"on",
"the",
"list",
"."
] | WoLpH/mailjet | python | https://github.com/WoLpH/mailjet/blob/f7f5102bf52be6a4a9c62afe474387481c806e27/mailjet/contrib/django_mailjet/forms.py#L38-L41 | [
"def",
"add_contact",
"(",
"self",
")",
":",
"self",
".",
"api",
".",
"lists",
".",
"addcontact",
"(",
"contact",
"=",
"self",
".",
"cleaned_data",
"[",
"'email'",
"]",
",",
"id",
"=",
"self",
".",
"list_id",
",",
"method",
"=",
"'POST'",
")"
] | f7f5102bf52be6a4a9c62afe474387481c806e27 |
train | SubscriptionForm.api | Get or create an Api() instance using django settings. | mailjet/contrib/django_mailjet/forms.py | def api(self):
""" Get or create an Api() instance using django settings. """
api = getattr(self, '_api', None)
if api is None:
self._api = mailjet.Api()
return self._api | def api(self):
""" Get or create an Api() instance using django settings. """
api = getattr(self, '_api', None)
if api is None:
self._api = mailjet.Api()
return self._api | [
"Get",
"or",
"create",
"an",
"Api",
"()",
"instance",
"using",
"django",
"settings",
"."
] | WoLpH/mailjet | python | https://github.com/WoLpH/mailjet/blob/f7f5102bf52be6a4a9c62afe474387481c806e27/mailjet/contrib/django_mailjet/forms.py#L44-L51 | [
"def",
"api",
"(",
"self",
")",
":",
"api",
"=",
"getattr",
"(",
"self",
",",
"'_api'",
",",
"None",
")",
"if",
"api",
"is",
"None",
":",
"self",
".",
"_api",
"=",
"mailjet",
".",
"Api",
"(",
")",
"return",
"self",
".",
"_api"
] | f7f5102bf52be6a4a9c62afe474387481c806e27 |
train | SubscriptionForm.list_id | Get or create the list id. | mailjet/contrib/django_mailjet/forms.py | def list_id(self):
""" Get or create the list id. """
list_id = getattr(self, '_list_id', None)
if list_id is None:
for l in self.api.lists.all()['lists']:
if l['name'] == self.list_name:
self._list_id = l['id']
if not getattr(self, '... | def list_id(self):
""" Get or create the list id. """
list_id = getattr(self, '_list_id', None)
if list_id is None:
for l in self.api.lists.all()['lists']:
if l['name'] == self.list_name:
self._list_id = l['id']
if not getattr(self, '... | [
"Get",
"or",
"create",
"the",
"list",
"id",
"."
] | WoLpH/mailjet | python | https://github.com/WoLpH/mailjet/blob/f7f5102bf52be6a4a9c62afe474387481c806e27/mailjet/contrib/django_mailjet/forms.py#L54-L68 | [
"def",
"list_id",
"(",
"self",
")",
":",
"list_id",
"=",
"getattr",
"(",
"self",
",",
"'_list_id'",
",",
"None",
")",
"if",
"list_id",
"is",
"None",
":",
"for",
"l",
"in",
"self",
".",
"api",
".",
"lists",
".",
"all",
"(",
")",
"[",
"'lists'",
"]... | f7f5102bf52be6a4a9c62afe474387481c806e27 |
train | getargspec | Portable version of inspect.getargspec().
Necessary because the original is no longer available
starting from Python 3.6.
:return: 4-tuple of (argnames, varargname, kwargname, defaults)
Note that distinction between positional-or-keyword and keyword-only
parameters will be lost, as the original g... | callee/_compat.py | def getargspec(obj):
"""Portable version of inspect.getargspec().
Necessary because the original is no longer available
starting from Python 3.6.
:return: 4-tuple of (argnames, varargname, kwargname, defaults)
Note that distinction between positional-or-keyword and keyword-only
parameters wil... | def getargspec(obj):
"""Portable version of inspect.getargspec().
Necessary because the original is no longer available
starting from Python 3.6.
:return: 4-tuple of (argnames, varargname, kwargname, defaults)
Note that distinction between positional-or-keyword and keyword-only
parameters wil... | [
"Portable",
"version",
"of",
"inspect",
".",
"getargspec",
"()",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/_compat.py#L81-L112 | [
"def",
"getargspec",
"(",
"obj",
")",
":",
"try",
":",
"return",
"inspect",
".",
"getargspec",
"(",
"obj",
")",
"except",
"AttributeError",
":",
"pass",
"# we let a TypeError through",
"# translate the signature object back into the 4-tuple",
"argnames",
"=",
"[",
"]"... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
train | read_tags | Reads values of "magic tags" defined in the given Python file.
:param filename: Python filename to read the tags from
:return: Dictionary of tags | setup.py | def read_tags(filename):
"""Reads values of "magic tags" defined in the given Python file.
:param filename: Python filename to read the tags from
:return: Dictionary of tags
"""
with open(filename) as f:
ast_tree = ast.parse(f.read(), filename)
res = {}
for node in ast.walk(ast_tre... | def read_tags(filename):
"""Reads values of "magic tags" defined in the given Python file.
:param filename: Python filename to read the tags from
:return: Dictionary of tags
"""
with open(filename) as f:
ast_tree = ast.parse(f.read(), filename)
res = {}
for node in ast.walk(ast_tre... | [
"Reads",
"values",
"of",
"magic",
"tags",
"defined",
"in",
"the",
"given",
"Python",
"file",
"."
] | Xion/callee | python | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/setup.py#L16-L39 | [
"def",
"read_tags",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"ast_tree",
"=",
"ast",
".",
"parse",
"(",
"f",
".",
"read",
"(",
")",
",",
"filename",
")",
"res",
"=",
"{",
"}",
"for",
"node",
"in",
"ast",
... | 58740f73ff9a76f5fe0075bf18d7345a0f9d961c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.