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 | _getSmallestDifference | Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast | promo/morph_utils/morph_sequence.py | def _getSmallestDifference(inputList, targetVal):
'''
Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast
'''
targetList = inputList[:]
retVal = None
while True:
# If we're down to one value, stop iterati... | def _getSmallestDifference(inputList, targetVal):
'''
Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast
'''
targetList = inputList[:]
retVal = None
while True:
# If we're down to one value, stop iterati... | [
"Returns",
"the",
"value",
"in",
"inputList",
"that",
"is",
"closest",
"to",
"targetVal",
"Iteratively",
"splits",
"the",
"dataset",
"in",
"two",
"so",
"it",
"should",
"be",
"pretty",
"fast"
] | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L98-L130 | [
"def",
"_getSmallestDifference",
"(",
"inputList",
",",
"targetVal",
")",
":",
"targetList",
"=",
"inputList",
"[",
":",
"]",
"retVal",
"=",
"None",
"while",
"True",
":",
"# If we're down to one value, stop iterating",
"if",
"len",
"(",
"targetList",
")",
"==",
... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | _getNearestMappingIndexList | Finds the indicies for data points that are closest to each other.
The inputs should be in relative time, scaled from 0 to 1
e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]
will output [0, 1, 1, 2] | promo/morph_utils/morph_sequence.py | def _getNearestMappingIndexList(fromValList, toValList):
'''
Finds the indicies for data points that are closest to each other.
The inputs should be in relative time, scaled from 0 to 1
e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]
will output [0, 1, 1, 2]
'''
indexList = []
for... | def _getNearestMappingIndexList(fromValList, toValList):
'''
Finds the indicies for data points that are closest to each other.
The inputs should be in relative time, scaled from 0 to 1
e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]
will output [0, 1, 1, 2]
'''
indexList = []
for... | [
"Finds",
"the",
"indicies",
"for",
"data",
"points",
"that",
"are",
"closest",
"to",
"each",
"other",
"."
] | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L133-L148 | [
"def",
"_getNearestMappingIndexList",
"(",
"fromValList",
",",
"toValList",
")",
":",
"indexList",
"=",
"[",
"]",
"for",
"fromTimestamp",
"in",
"fromValList",
":",
"smallestDiff",
"=",
"_getSmallestDifference",
"(",
"toValList",
",",
"fromTimestamp",
")",
"i",
"="... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | morphDataLists | Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value | promo/morph_utils/morph_sequence.py | def morphDataLists(fromList, toList, stepList):
'''
Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value
'''
# If there are more than 1 pitch value, then we align the da... | def morphDataLists(fromList, toList, stepList):
'''
Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value
'''
# If there are more than 1 pitch value, then we align the da... | [
"Iteratively",
"morph",
"fromList",
"into",
"toList",
"using",
"the",
"values",
"0",
"to",
"1",
"in",
"stepList",
"stepList",
":",
"a",
"value",
"of",
"0",
"means",
"no",
"change",
"and",
"a",
"value",
"of",
"1",
"means",
"a",
"complete",
"change",
"to",... | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L151-L194 | [
"def",
"morphDataLists",
"(",
"fromList",
",",
"toList",
",",
"stepList",
")",
":",
"# If there are more than 1 pitch value, then we align the data in",
"# relative time.",
"# Each data point comes with a timestamp. The earliest timestamp is 0",
"# and the latest timestamp is 1. Using th... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | morphChunkedDataLists | Morph one set of data into another, in a stepwise fashion
A convenience function. Given a set of paired data lists,
this will morph each one individually.
Returns a single list with all data combined together. | promo/morph_utils/morph_sequence.py | def morphChunkedDataLists(fromDataList, toDataList, stepList):
'''
Morph one set of data into another, in a stepwise fashion
A convenience function. Given a set of paired data lists,
this will morph each one individually.
Returns a single list with all data combined together.
'''
assert(... | def morphChunkedDataLists(fromDataList, toDataList, stepList):
'''
Morph one set of data into another, in a stepwise fashion
A convenience function. Given a set of paired data lists,
this will morph each one individually.
Returns a single list with all data combined together.
'''
assert(... | [
"Morph",
"one",
"set",
"of",
"data",
"into",
"another",
"in",
"a",
"stepwise",
"fashion"
] | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L197-L228 | [
"def",
"morphChunkedDataLists",
"(",
"fromDataList",
",",
"toDataList",
",",
"stepList",
")",
":",
"assert",
"(",
"len",
"(",
"fromDataList",
")",
"==",
"len",
"(",
"toDataList",
")",
")",
"# Morph the fromDataList into the toDataList",
"outputList",
"=",
"[",
"]"... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | morphAveragePitch | Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code removes any values below zero, thus the
final average might no... | promo/morph_utils/morph_sequence.py | def morphAveragePitch(fromDataList, toDataList):
'''
Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code remov... | def morphAveragePitch(fromDataList, toDataList):
'''
Adjusts the values in fromPitchList to have the same average as toPitchList
Because other manipulations can alter the average pitch, morphing the pitch
is the last pitch manipulation that should be done
After the morphing, the code remov... | [
"Adjusts",
"the",
"values",
"in",
"fromPitchList",
"to",
"have",
"the",
"same",
"average",
"as",
"toPitchList",
"Because",
"other",
"manipulations",
"can",
"alter",
"the",
"average",
"pitch",
"morphing",
"the",
"pitch",
"is",
"the",
"last",
"pitch",
"manipulatio... | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L231-L262 | [
"def",
"morphAveragePitch",
"(",
"fromDataList",
",",
"toDataList",
")",
":",
"timeList",
",",
"fromPitchList",
"=",
"zip",
"(",
"*",
"fromDataList",
")",
"toPitchList",
"=",
"[",
"pitchVal",
"for",
"_",
",",
"pitchVal",
"in",
"toDataList",
"]",
"# Zero pitch ... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | morphRange | Changes the scale of values in one distribution to that of another
ie The maximum value in fromDataList will be set to the maximum value in
toDataList. The 75% largest value in fromDataList will be set to the
75% largest value in toDataList, etc.
Small sample sizes will yield results that are... | promo/morph_utils/morph_sequence.py | def morphRange(fromDataList, toDataList):
'''
Changes the scale of values in one distribution to that of another
ie The maximum value in fromDataList will be set to the maximum value in
toDataList. The 75% largest value in fromDataList will be set to the
75% largest value in toDataList, etc.
... | def morphRange(fromDataList, toDataList):
'''
Changes the scale of values in one distribution to that of another
ie The maximum value in fromDataList will be set to the maximum value in
toDataList. The 75% largest value in fromDataList will be set to the
75% largest value in toDataList, etc.
... | [
"Changes",
"the",
"scale",
"of",
"values",
"in",
"one",
"distribution",
"to",
"that",
"of",
"another",
"ie",
"The",
"maximum",
"value",
"in",
"fromDataList",
"will",
"be",
"set",
"to",
"the",
"maximum",
"value",
"in",
"toDataList",
".",
"The",
"75%",
"larg... | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L265-L301 | [
"def",
"morphRange",
"(",
"fromDataList",
",",
"toDataList",
")",
":",
"# Isolate and sort pitch values",
"fromPitchList",
"=",
"[",
"dataTuple",
"[",
"1",
"]",
"for",
"dataTuple",
"in",
"fromDataList",
"]",
"toPitchList",
"=",
"[",
"dataTuple",
"[",
"1",
"]",
... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | quadraticInterpolation | Generates a series of points on a smooth curve that cross the given points
numDegrees - the degrees of the fitted polynomial
- the curve gets weird if this value is too high for the input
n - number of points to output
startTime/endTime/n - n points will be generated at evenly spaced
... | promo/morph_utils/interpolation.py | def quadraticInterpolation(valueList2d, numDegrees, n,
startTime=None, endTime=None):
'''
Generates a series of points on a smooth curve that cross the given points
numDegrees - the degrees of the fitted polynomial
- the curve gets weird if this value is too hi... | def quadraticInterpolation(valueList2d, numDegrees, n,
startTime=None, endTime=None):
'''
Generates a series of points on a smooth curve that cross the given points
numDegrees - the degrees of the fitted polynomial
- the curve gets weird if this value is too hi... | [
"Generates",
"a",
"series",
"of",
"points",
"on",
"a",
"smooth",
"curve",
"that",
"cross",
"the",
"given",
"points",
"numDegrees",
"-",
"the",
"degrees",
"of",
"the",
"fitted",
"polynomial",
"-",
"the",
"curve",
"gets",
"weird",
"if",
"this",
"value",
"is"... | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/interpolation.py#L21-L47 | [
"def",
"quadraticInterpolation",
"(",
"valueList2d",
",",
"numDegrees",
",",
"n",
",",
"startTime",
"=",
"None",
",",
"endTime",
"=",
"None",
")",
":",
"_numpyCheck",
"(",
")",
"x",
",",
"y",
"=",
"zip",
"(",
"*",
"valueList2d",
")",
"if",
"startTime",
... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | getIntervals | Get information about the 'extract' tier, used by several merge scripts | promo/morph_utils/utils.py | def getIntervals(fn, tierName, filterFunc=None,
includeUnlabeledRegions=False):
'''
Get information about the 'extract' tier, used by several merge scripts
'''
tg = tgio.openTextgrid(fn)
tier = tg.tierDict[tierName]
if includeUnlabeledRegions is True:
tier = tgio._... | def getIntervals(fn, tierName, filterFunc=None,
includeUnlabeledRegions=False):
'''
Get information about the 'extract' tier, used by several merge scripts
'''
tg = tgio.openTextgrid(fn)
tier = tg.tierDict[tierName]
if includeUnlabeledRegions is True:
tier = tgio._... | [
"Get",
"information",
"about",
"the",
"extract",
"tier",
"used",
"by",
"several",
"merge",
"scripts"
] | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/utils.py#L12-L28 | [
"def",
"getIntervals",
"(",
"fn",
",",
"tierName",
",",
"filterFunc",
"=",
"None",
",",
"includeUnlabeledRegions",
"=",
"False",
")",
":",
"tg",
"=",
"tgio",
".",
"openTextgrid",
"(",
"fn",
")",
"tier",
"=",
"tg",
".",
"tierDict",
"[",
"tierName",
"]",
... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | changeDuration | Uses praat to morph duration in one file to duration in another
Praat uses the PSOLA algorithm | promo/duration_morph.py | def changeDuration(fromWavFN, durationParameters, stepList, outputName,
outputMinPitch, outputMaxPitch, praatEXE):
'''
Uses praat to morph duration in one file to duration in another
Praat uses the PSOLA algorithm
'''
rootPath = os.path.split(fromWavFN)[0]
# Prep output dir... | def changeDuration(fromWavFN, durationParameters, stepList, outputName,
outputMinPitch, outputMaxPitch, praatEXE):
'''
Uses praat to morph duration in one file to duration in another
Praat uses the PSOLA algorithm
'''
rootPath = os.path.split(fromWavFN)[0]
# Prep output dir... | [
"Uses",
"praat",
"to",
"morph",
"duration",
"in",
"one",
"file",
"to",
"duration",
"in",
"another"
] | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/duration_morph.py#L35-L87 | [
"def",
"changeDuration",
"(",
"fromWavFN",
",",
"durationParameters",
",",
"stepList",
",",
"outputName",
",",
"outputMinPitch",
",",
"outputMaxPitch",
",",
"praatEXE",
")",
":",
"rootPath",
"=",
"os",
".",
"path",
".",
"split",
"(",
"fromWavFN",
")",
"[",
"... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | getMorphParameters | Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on the contents of toTGFN. | promo/duration_morph.py | def getMorphParameters(fromTGFN, toTGFN, tierName,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on the contents of ... | def getMorphParameters(fromTGFN, toTGFN, tierName,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on the contents of ... | [
"Get",
"intervals",
"for",
"source",
"and",
"target",
"audio",
"files",
"Use",
"this",
"information",
"to",
"find",
"out",
"how",
"much",
"to",
"stretch",
"/",
"shrink",
"each",
"source",
"interval",
".",
"The",
"target",
"values",
"are",
"based",
"on",
"t... | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/duration_morph.py#L95-L133 | [
"def",
"getMorphParameters",
"(",
"fromTGFN",
",",
"toTGFN",
",",
"tierName",
",",
"filterFunc",
"=",
"None",
",",
"useBlanks",
"=",
"False",
")",
":",
"if",
"filterFunc",
"is",
"None",
":",
"filterFunc",
"=",
"lambda",
"entry",
":",
"True",
"# Everything is... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | getManipulatedParamaters | Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on modfunc. | promo/duration_morph.py | def getManipulatedParamaters(tgFN, tierName, modFunc,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on modfunc... | def getManipulatedParamaters(tgFN, tierName, modFunc,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on modfunc... | [
"Get",
"intervals",
"for",
"source",
"and",
"target",
"audio",
"files",
"Use",
"this",
"information",
"to",
"find",
"out",
"how",
"much",
"to",
"stretch",
"/",
"shrink",
"each",
"source",
"interval",
".",
"The",
"target",
"values",
"are",
"based",
"on",
"m... | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/duration_morph.py#L136-L166 | [
"def",
"getManipulatedParamaters",
"(",
"tgFN",
",",
"tierName",
",",
"modFunc",
",",
"filterFunc",
"=",
"None",
",",
"useBlanks",
"=",
"False",
")",
":",
"fromExtractInfo",
"=",
"utils",
".",
"getIntervals",
"(",
"tgFN",
",",
"tierName",
",",
"filterFunc",
... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | textgridMorphDuration | A convenience function. Morphs interval durations of one tg to another.
This assumes the two textgrids have the same number of segments. | promo/duration_morph.py | def textgridMorphDuration(fromTGFN, toTGFN):
'''
A convenience function. Morphs interval durations of one tg to another.
This assumes the two textgrids have the same number of segments.
'''
fromTG = tgio.openTextgrid(fromTGFN)
toTG = tgio.openTextgrid(toTGFN)
adjustedTG = tgio.Textgrid... | def textgridMorphDuration(fromTGFN, toTGFN):
'''
A convenience function. Morphs interval durations of one tg to another.
This assumes the two textgrids have the same number of segments.
'''
fromTG = tgio.openTextgrid(fromTGFN)
toTG = tgio.openTextgrid(toTGFN)
adjustedTG = tgio.Textgrid... | [
"A",
"convenience",
"function",
".",
"Morphs",
"interval",
"durations",
"of",
"one",
"tg",
"to",
"another",
".",
"This",
"assumes",
"the",
"two",
"textgrids",
"have",
"the",
"same",
"number",
"of",
"segments",
"."
] | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/duration_morph.py#L244-L260 | [
"def",
"textgridMorphDuration",
"(",
"fromTGFN",
",",
"toTGFN",
")",
":",
"fromTG",
"=",
"tgio",
".",
"openTextgrid",
"(",
"fromTGFN",
")",
"toTG",
"=",
"tgio",
".",
"openTextgrid",
"(",
"toTGFN",
")",
"adjustedTG",
"=",
"tgio",
".",
"Textgrid",
"(",
")",
... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | getSoundFileDuration | Returns the duration of a wav file (in seconds) | promo/morph_utils/audio_scripts.py | def getSoundFileDuration(fn):
'''
Returns the duration of a wav file (in seconds)
'''
audiofile = wave.open(fn, "r")
params = audiofile.getparams()
framerate = params[2]
nframes = params[3]
duration = float(nframes) / framerate
return duration | def getSoundFileDuration(fn):
'''
Returns the duration of a wav file (in seconds)
'''
audiofile = wave.open(fn, "r")
params = audiofile.getparams()
framerate = params[2]
nframes = params[3]
duration = float(nframes) / framerate
return duration | [
"Returns",
"the",
"duration",
"of",
"a",
"wav",
"file",
"(",
"in",
"seconds",
")"
] | timmahrt/ProMo | python | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/audio_scripts.py#L10-L21 | [
"def",
"getSoundFileDuration",
"(",
"fn",
")",
":",
"audiofile",
"=",
"wave",
".",
"open",
"(",
"fn",
",",
"\"r\"",
")",
"params",
"=",
"audiofile",
".",
"getparams",
"(",
")",
"framerate",
"=",
"params",
"[",
"2",
"]",
"nframes",
"=",
"params",
"[",
... | 99d9f5cc01ff328a62973c5a5da910cc905ae4d5 |
train | split_text | u"""
Split Chinese text at word boundaries.
include_pos: also returns the Part Of Speech for each of the words.
Some of the different parts of speech are:
r: pronoun
v: verb
ns: proper noun
etc...
This all gets returned as a tuple:
index 0: the split word
... | mafan/text.py | def split_text(text, include_part_of_speech=False, strip_english=False, strip_numbers=False):
u"""
Split Chinese text at word boundaries.
include_pos: also returns the Part Of Speech for each of the words.
Some of the different parts of speech are:
r: pronoun
v: verb
ns: proper ... | def split_text(text, include_part_of_speech=False, strip_english=False, strip_numbers=False):
u"""
Split Chinese text at word boundaries.
include_pos: also returns the Part Of Speech for each of the words.
Some of the different parts of speech are:
r: pronoun
v: verb
ns: proper ... | [
"u",
"Split",
"Chinese",
"text",
"at",
"word",
"boundaries",
"."
] | hermanschaaf/mafan | python | https://github.com/hermanschaaf/mafan/blob/373ddf299aeb2bd8413bf921c71768af7a8170ea/mafan/text.py#L209-L246 | [
"def",
"split_text",
"(",
"text",
",",
"include_part_of_speech",
"=",
"False",
",",
"strip_english",
"=",
"False",
",",
"strip_numbers",
"=",
"False",
")",
":",
"if",
"not",
"include_part_of_speech",
":",
"seg_list",
"=",
"pseg",
".",
"cut",
"(",
"text",
")"... | 373ddf299aeb2bd8413bf921c71768af7a8170ea |
train | is_special_atom | Returns a boolean indicating whether or not the string can be parsed by
parse_atom to produce a static set. In the process of examining the
string, the syntax of any special character uses is also checked. | cronex/__init__.py | def is_special_atom(cron_atom, span):
"""
Returns a boolean indicating whether or not the string can be parsed by
parse_atom to produce a static set. In the process of examining the
string, the syntax of any special character uses is also checked.
"""
for special_char in ('%', '#', 'L', 'W'):
... | def is_special_atom(cron_atom, span):
"""
Returns a boolean indicating whether or not the string can be parsed by
parse_atom to produce a static set. In the process of examining the
string, the syntax of any special character uses is also checked.
"""
for special_char in ('%', '#', 'L', 'W'):
... | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"or",
"not",
"the",
"string",
"can",
"be",
"parsed",
"by",
"parse_atom",
"to",
"produce",
"a",
"static",
"set",
".",
"In",
"the",
"process",
"of",
"examining",
"the",
"string",
"the",
"syntax",
"of",
"any... | ericpruitt/cronex | python | https://github.com/ericpruitt/cronex/blob/ff48a3a71bbcdf01cff46c0bf9376e69492c9224/cronex/__init__.py#L264-L298 | [
"def",
"is_special_atom",
"(",
"cron_atom",
",",
"span",
")",
":",
"for",
"special_char",
"in",
"(",
"'%'",
",",
"'#'",
",",
"'L'",
",",
"'W'",
")",
":",
"if",
"special_char",
"not",
"in",
"cron_atom",
":",
"continue",
"if",
"special_char",
"==",
"'#'",
... | ff48a3a71bbcdf01cff46c0bf9376e69492c9224 |
train | parse_atom | Returns a set containing valid values for a given cron-style range of
numbers. The 'minmax' arguments is a two element iterable containing the
inclusive upper and lower limits of the expression.
Examples:
>>> parse_atom("1-5",(0,6))
set([1, 2, 3, 4, 5])
>>> parse_atom("*/6",(0,23))
set([0,... | cronex/__init__.py | def parse_atom(parse, minmax):
"""
Returns a set containing valid values for a given cron-style range of
numbers. The 'minmax' arguments is a two element iterable containing the
inclusive upper and lower limits of the expression.
Examples:
>>> parse_atom("1-5",(0,6))
set([1, 2, 3, 4, 5])
... | def parse_atom(parse, minmax):
"""
Returns a set containing valid values for a given cron-style range of
numbers. The 'minmax' arguments is a two element iterable containing the
inclusive upper and lower limits of the expression.
Examples:
>>> parse_atom("1-5",(0,6))
set([1, 2, 3, 4, 5])
... | [
"Returns",
"a",
"set",
"containing",
"valid",
"values",
"for",
"a",
"given",
"cron",
"-",
"style",
"range",
"of",
"numbers",
".",
"The",
"minmax",
"arguments",
"is",
"a",
"two",
"element",
"iterable",
"containing",
"the",
"inclusive",
"upper",
"and",
"lower"... | ericpruitt/cronex | python | https://github.com/ericpruitt/cronex/blob/ff48a3a71bbcdf01cff46c0bf9376e69492c9224/cronex/__init__.py#L302-L362 | [
"def",
"parse_atom",
"(",
"parse",
",",
"minmax",
")",
":",
"parse",
"=",
"parse",
".",
"strip",
"(",
")",
"increment",
"=",
"1",
"if",
"parse",
"==",
"'*'",
":",
"return",
"set",
"(",
"xrange",
"(",
"minmax",
"[",
"0",
"]",
",",
"minmax",
"[",
"... | ff48a3a71bbcdf01cff46c0bf9376e69492c9224 |
train | CronExpression.compute_numtab | Recomputes the sets for the static ranges of the trigger time.
This method should only be called by the user if the string_tab
member is modified. | cronex/__init__.py | def compute_numtab(self):
"""
Recomputes the sets for the static ranges of the trigger time.
This method should only be called by the user if the string_tab
member is modified.
"""
self.numerical_tab = []
for field_str, span in zip(self.string_tab, FIELD_RANGES)... | def compute_numtab(self):
"""
Recomputes the sets for the static ranges of the trigger time.
This method should only be called by the user if the string_tab
member is modified.
"""
self.numerical_tab = []
for field_str, span in zip(self.string_tab, FIELD_RANGES)... | [
"Recomputes",
"the",
"sets",
"for",
"the",
"static",
"ranges",
"of",
"the",
"trigger",
"time",
"."
] | ericpruitt/cronex | python | https://github.com/ericpruitt/cronex/blob/ff48a3a71bbcdf01cff46c0bf9376e69492c9224/cronex/__init__.py#L129-L154 | [
"def",
"compute_numtab",
"(",
"self",
")",
":",
"self",
".",
"numerical_tab",
"=",
"[",
"]",
"for",
"field_str",
",",
"span",
"in",
"zip",
"(",
"self",
".",
"string_tab",
",",
"FIELD_RANGES",
")",
":",
"split_field_str",
"=",
"field_str",
".",
"split",
"... | ff48a3a71bbcdf01cff46c0bf9376e69492c9224 |
train | CronExpression.check_trigger | Returns boolean indicating if the trigger is active at the given time.
The date tuple should be in the local time. Unless periodicities are
used, utc_offset does not need to be specified. If periodicities are
used, specifically in the hour and minutes fields, it is crucial that
the utc_o... | cronex/__init__.py | def check_trigger(self, date_tuple, utc_offset=0):
"""
Returns boolean indicating if the trigger is active at the given time.
The date tuple should be in the local time. Unless periodicities are
used, utc_offset does not need to be specified. If periodicities are
used, specifical... | def check_trigger(self, date_tuple, utc_offset=0):
"""
Returns boolean indicating if the trigger is active at the given time.
The date tuple should be in the local time. Unless periodicities are
used, utc_offset does not need to be specified. If periodicities are
used, specifical... | [
"Returns",
"boolean",
"indicating",
"if",
"the",
"trigger",
"is",
"active",
"at",
"the",
"given",
"time",
".",
"The",
"date",
"tuple",
"should",
"be",
"in",
"the",
"local",
"time",
".",
"Unless",
"periodicities",
"are",
"used",
"utc_offset",
"does",
"not",
... | ericpruitt/cronex | python | https://github.com/ericpruitt/cronex/blob/ff48a3a71bbcdf01cff46c0bf9376e69492c9224/cronex/__init__.py#L156-L261 | [
"def",
"check_trigger",
"(",
"self",
",",
"date_tuple",
",",
"utc_offset",
"=",
"0",
")",
":",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"mins",
"=",
"date_tuple",
"given_date",
"=",
"datetime",
".",
"date",
"(",
"year",
",",
"month",
",",
... | ff48a3a71bbcdf01cff46c0bf9376e69492c9224 |
train | Rule.show | Show the structure of self.rules_list, only for debug. | permission/permission.py | def show(self):
"""Show the structure of self.rules_list, only for debug."""
for rule in self.rules_list:
result = ", ".join([str(check) for check, deny in rule])
print(result) | def show(self):
"""Show the structure of self.rules_list, only for debug."""
for rule in self.rules_list:
result = ", ".join([str(check) for check, deny in rule])
print(result) | [
"Show",
"the",
"structure",
"of",
"self",
".",
"rules_list",
"only",
"for",
"debug",
"."
] | hustlzp/permission | python | https://github.com/hustlzp/permission/blob/302a02a775c4cd53f7588ff9c4ce1ca49a0d40bf/permission/permission.py#L88-L92 | [
"def",
"show",
"(",
"self",
")",
":",
"for",
"rule",
"in",
"self",
".",
"rules_list",
":",
"result",
"=",
"\", \"",
".",
"join",
"(",
"[",
"str",
"(",
"check",
")",
"for",
"check",
",",
"deny",
"in",
"rule",
"]",
")",
"print",
"(",
"result",
")"
... | 302a02a775c4cd53f7588ff9c4ce1ca49a0d40bf |
train | Rule.run | Run self.rules_list.
Return True if one rule channel has been passed.
Otherwise return False and the deny() method of the last failed rule. | permission/permission.py | def run(self):
"""Run self.rules_list.
Return True if one rule channel has been passed.
Otherwise return False and the deny() method of the last failed rule.
"""
failed_result = None
for rule in self.rules_list:
for check, deny in rule:
if not... | def run(self):
"""Run self.rules_list.
Return True if one rule channel has been passed.
Otherwise return False and the deny() method of the last failed rule.
"""
failed_result = None
for rule in self.rules_list:
for check, deny in rule:
if not... | [
"Run",
"self",
".",
"rules_list",
"."
] | hustlzp/permission | python | https://github.com/hustlzp/permission/blob/302a02a775c4cd53f7588ff9c4ce1ca49a0d40bf/permission/permission.py#L98-L112 | [
"def",
"run",
"(",
"self",
")",
":",
"failed_result",
"=",
"None",
"for",
"rule",
"in",
"self",
".",
"rules_list",
":",
"for",
"check",
",",
"deny",
"in",
"rule",
":",
"if",
"not",
"check",
"(",
")",
":",
"failed_result",
"=",
"(",
"False",
",",
"d... | 302a02a775c4cd53f7588ff9c4ce1ca49a0d40bf |
train | MeterRectangle.set_fraction | Set the meter indicator. Value should be between 0 and 1. | fritzconnection/fritzmonitor.py | def set_fraction(self, value):
"""Set the meter indicator. Value should be between 0 and 1."""
if value < 0:
value *= -1
value = min(value, 1)
if self.horizontal:
width = int(self.width * value)
height = self.height
else:
width = se... | def set_fraction(self, value):
"""Set the meter indicator. Value should be between 0 and 1."""
if value < 0:
value *= -1
value = min(value, 1)
if self.horizontal:
width = int(self.width * value)
height = self.height
else:
width = se... | [
"Set",
"the",
"meter",
"indicator",
".",
"Value",
"should",
"be",
"between",
"0",
"and",
"1",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzmonitor.py#L58-L70 | [
"def",
"set_fraction",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"<",
"0",
":",
"value",
"*=",
"-",
"1",
"value",
"=",
"min",
"(",
"value",
",",
"1",
")",
"if",
"self",
".",
"horizontal",
":",
"width",
"=",
"int",
"(",
"self",
".",
"w... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzMonitor.update_status | Update status informations in tkinter window. | fritzconnection/fritzmonitor.py | def update_status(self):
"""Update status informations in tkinter window."""
try:
# all this may fail if the connection to the fritzbox is down
self.update_connection_status()
self.max_stream_rate.set(self.get_stream_rate_str())
self.ip.set(self.status.ext... | def update_status(self):
"""Update status informations in tkinter window."""
try:
# all this may fail if the connection to the fritzbox is down
self.update_connection_status()
self.max_stream_rate.set(self.get_stream_rate_str())
self.ip.set(self.status.ext... | [
"Update",
"status",
"informations",
"in",
"tkinter",
"window",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzmonitor.py#L112-L134 | [
"def",
"update_status",
"(",
"self",
")",
":",
"try",
":",
"# all this may fail if the connection to the fritzbox is down",
"self",
".",
"update_connection_status",
"(",
")",
"self",
".",
"max_stream_rate",
".",
"set",
"(",
"self",
".",
"get_stream_rate_str",
"(",
")"... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | format_num | Returns a human readable string of a byte-value.
If 'num' is bits, set unit='bits'. | fritzconnection/fritztools.py | def format_num(num, unit='bytes'):
"""
Returns a human readable string of a byte-value.
If 'num' is bits, set unit='bits'.
"""
if unit == 'bytes':
extension = 'B'
else:
# if it's not bytes, it's bits
extension = 'Bit'
for dimension in (unit, 'K', 'M', 'G', 'T'):
... | def format_num(num, unit='bytes'):
"""
Returns a human readable string of a byte-value.
If 'num' is bits, set unit='bits'.
"""
if unit == 'bytes':
extension = 'B'
else:
# if it's not bytes, it's bits
extension = 'Bit'
for dimension in (unit, 'K', 'M', 'G', 'T'):
... | [
"Returns",
"a",
"human",
"readable",
"string",
"of",
"a",
"byte",
"-",
"value",
".",
"If",
"num",
"is",
"bits",
"set",
"unit",
"=",
"bits",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritztools.py#L9-L25 | [
"def",
"format_num",
"(",
"num",
",",
"unit",
"=",
"'bytes'",
")",
":",
"if",
"unit",
"==",
"'bytes'",
":",
"extension",
"=",
"'B'",
"else",
":",
"# if it's not bytes, it's bits",
"extension",
"=",
"'Bit'",
"for",
"dimension",
"in",
"(",
"unit",
",",
"'K'"... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | parse_headers | Build a ContentDisposition from header values. | rfc6266.py | def parse_headers(content_disposition, location=None, relaxed=False):
"""Build a ContentDisposition from header values.
"""
LOGGER.debug(
'Content-Disposition %r, Location %r', content_disposition, location)
if content_disposition is None:
return ContentDisposition(location=location)
... | def parse_headers(content_disposition, location=None, relaxed=False):
"""Build a ContentDisposition from header values.
"""
LOGGER.debug(
'Content-Disposition %r, Location %r', content_disposition, location)
if content_disposition is None:
return ContentDisposition(location=location)
... | [
"Build",
"a",
"ContentDisposition",
"from",
"header",
"values",
"."
] | g2p/rfc6266 | python | https://github.com/g2p/rfc6266/blob/cad58963ed13f5e1068fcc9e4326123b6b2bdcf8/rfc6266.py#L175-L232 | [
"def",
"parse_headers",
"(",
"content_disposition",
",",
"location",
"=",
"None",
",",
"relaxed",
"=",
"False",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Content-Disposition %r, Location %r'",
",",
"content_disposition",
",",
"location",
")",
"if",
"content_dispositi... | cad58963ed13f5e1068fcc9e4326123b6b2bdcf8 |
train | parse_requests_response | Build a ContentDisposition from a requests (PyPI) response. | rfc6266.py | def parse_requests_response(response, **kwargs):
"""Build a ContentDisposition from a requests (PyPI) response.
"""
return parse_headers(
response.headers.get('content-disposition'), response.url, **kwargs) | def parse_requests_response(response, **kwargs):
"""Build a ContentDisposition from a requests (PyPI) response.
"""
return parse_headers(
response.headers.get('content-disposition'), response.url, **kwargs) | [
"Build",
"a",
"ContentDisposition",
"from",
"a",
"requests",
"(",
"PyPI",
")",
"response",
"."
] | g2p/rfc6266 | python | https://github.com/g2p/rfc6266/blob/cad58963ed13f5e1068fcc9e4326123b6b2bdcf8/rfc6266.py#L244-L249 | [
"def",
"parse_requests_response",
"(",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"parse_headers",
"(",
"response",
".",
"headers",
".",
"get",
"(",
"'content-disposition'",
")",
",",
"response",
".",
"url",
",",
"*",
"*",
"kwargs",
")"
] | cad58963ed13f5e1068fcc9e4326123b6b2bdcf8 |
train | build_header | Generate a Content-Disposition header for a given filename.
For legacy clients that don't understand the filename* parameter,
a filename_compat value may be given.
It should either be ascii-only (recommended) or iso-8859-1 only.
In the later case it should be a character string
(unicode in Python 2... | rfc6266.py | def build_header(
filename, disposition='attachment', filename_compat=None
):
"""Generate a Content-Disposition header for a given filename.
For legacy clients that don't understand the filename* parameter,
a filename_compat value may be given.
It should either be ascii-only (recommended) or iso-88... | def build_header(
filename, disposition='attachment', filename_compat=None
):
"""Generate a Content-Disposition header for a given filename.
For legacy clients that don't understand the filename* parameter,
a filename_compat value may be given.
It should either be ascii-only (recommended) or iso-88... | [
"Generate",
"a",
"Content",
"-",
"Disposition",
"header",
"for",
"a",
"given",
"filename",
"."
] | g2p/rfc6266 | python | https://github.com/g2p/rfc6266/blob/cad58963ed13f5e1068fcc9e4326123b6b2bdcf8/rfc6266.py#L398-L453 | [
"def",
"build_header",
"(",
"filename",
",",
"disposition",
"=",
"'attachment'",
",",
"filename_compat",
"=",
"None",
")",
":",
"# While this method exists, it could also sanitize the filename",
"# by rejecting slashes or other weirdness that might upset a receiver.",
"if",
"dispos... | cad58963ed13f5e1068fcc9e4326123b6b2bdcf8 |
train | ContentDisposition.filename_unsafe | The filename from the Content-Disposition header.
If a location was passed at instanciation, the basename
from that may be used as a fallback. Otherwise, this may
be the None value.
On safety:
This property records the intent of the sender.
You shouldn't use th... | rfc6266.py | def filename_unsafe(self):
"""The filename from the Content-Disposition header.
If a location was passed at instanciation, the basename
from that may be used as a fallback. Otherwise, this may
be the None value.
On safety:
This property records the intent of the sen... | def filename_unsafe(self):
"""The filename from the Content-Disposition header.
If a location was passed at instanciation, the basename
from that may be used as a fallback. Otherwise, this may
be the None value.
On safety:
This property records the intent of the sen... | [
"The",
"filename",
"from",
"the",
"Content",
"-",
"Disposition",
"header",
"."
] | g2p/rfc6266 | python | https://github.com/g2p/rfc6266/blob/cad58963ed13f5e1068fcc9e4326123b6b2bdcf8/rfc6266.py#L89-L112 | [
"def",
"filename_unsafe",
"(",
"self",
")",
":",
"if",
"'filename*'",
"in",
"self",
".",
"assocs",
":",
"return",
"self",
".",
"assocs",
"[",
"'filename*'",
"]",
".",
"string",
"elif",
"'filename'",
"in",
"self",
".",
"assocs",
":",
"# XXX Reject non-ascii (... | cad58963ed13f5e1068fcc9e4326123b6b2bdcf8 |
train | ContentDisposition.filename_sanitized | Returns a filename that is safer to use on the filesystem.
The filename will not contain a slash (nor the path separator
for the current platform, if different), it will not
start with a dot, and it will have the expected extension.
No guarantees that makes it "safe enough".
No... | rfc6266.py | def filename_sanitized(self, extension, default_filename='file'):
"""Returns a filename that is safer to use on the filesystem.
The filename will not contain a slash (nor the path separator
for the current platform, if different), it will not
start with a dot, and it will have the expec... | def filename_sanitized(self, extension, default_filename='file'):
"""Returns a filename that is safer to use on the filesystem.
The filename will not contain a slash (nor the path separator
for the current platform, if different), it will not
start with a dot, and it will have the expec... | [
"Returns",
"a",
"filename",
"that",
"is",
"safer",
"to",
"use",
"on",
"the",
"filesystem",
"."
] | g2p/rfc6266 | python | https://github.com/g2p/rfc6266/blob/cad58963ed13f5e1068fcc9e4326123b6b2bdcf8/rfc6266.py#L121-L149 | [
"def",
"filename_sanitized",
"(",
"self",
",",
"extension",
",",
"default_filename",
"=",
"'file'",
")",
":",
"assert",
"extension",
"assert",
"extension",
"[",
"0",
"]",
"!=",
"'.'",
"assert",
"default_filename",
"assert",
"'.'",
"not",
"in",
"default_filename"... | cad58963ed13f5e1068fcc9e4326123b6b2bdcf8 |
train | FritzStatus.str_uptime | uptime in human readable format. | fritzconnection/fritzstatus.py | def str_uptime(self):
"""uptime in human readable format."""
mins, secs = divmod(self.uptime, 60)
hours, mins = divmod(mins, 60)
return '%02d:%02d:%02d' % (hours, mins, secs) | def str_uptime(self):
"""uptime in human readable format."""
mins, secs = divmod(self.uptime, 60)
hours, mins = divmod(mins, 60)
return '%02d:%02d:%02d' % (hours, mins, secs) | [
"uptime",
"in",
"human",
"readable",
"format",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L82-L86 | [
"def",
"str_uptime",
"(",
"self",
")",
":",
"mins",
",",
"secs",
"=",
"divmod",
"(",
"self",
".",
"uptime",
",",
"60",
")",
"hours",
",",
"mins",
"=",
"divmod",
"(",
"mins",
",",
"60",
")",
"return",
"'%02d:%02d:%02d'",
"%",
"(",
"hours",
",",
"min... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzStatus.transmission_rate | Returns the upstream, downstream values as a tuple in bytes per
second. Use this for periodical calling. | fritzconnection/fritzstatus.py | def transmission_rate(self):
"""
Returns the upstream, downstream values as a tuple in bytes per
second. Use this for periodical calling.
"""
sent = self.bytes_sent
received = self.bytes_received
traffic_call = time.time()
time_delta = traffic_call - self.... | def transmission_rate(self):
"""
Returns the upstream, downstream values as a tuple in bytes per
second. Use this for periodical calling.
"""
sent = self.bytes_sent
received = self.bytes_received
traffic_call = time.time()
time_delta = traffic_call - self.... | [
"Returns",
"the",
"upstream",
"downstream",
"values",
"as",
"a",
"tuple",
"in",
"bytes",
"per",
"second",
".",
"Use",
"this",
"for",
"periodical",
"calling",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L101-L115 | [
"def",
"transmission_rate",
"(",
"self",
")",
":",
"sent",
"=",
"self",
".",
"bytes_sent",
"received",
"=",
"self",
".",
"bytes_received",
"traffic_call",
"=",
"time",
".",
"time",
"(",
")",
"time_delta",
"=",
"traffic_call",
"-",
"self",
".",
"last_traffic_... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzStatus.str_transmission_rate | Returns a tuple of human readable transmission rates in bytes. | fritzconnection/fritzstatus.py | def str_transmission_rate(self):
"""Returns a tuple of human readable transmission rates in bytes."""
upstream, downstream = self.transmission_rate
return (
fritztools.format_num(upstream),
fritztools.format_num(downstream)
) | def str_transmission_rate(self):
"""Returns a tuple of human readable transmission rates in bytes."""
upstream, downstream = self.transmission_rate
return (
fritztools.format_num(upstream),
fritztools.format_num(downstream)
) | [
"Returns",
"a",
"tuple",
"of",
"human",
"readable",
"transmission",
"rates",
"in",
"bytes",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L118-L124 | [
"def",
"str_transmission_rate",
"(",
"self",
")",
":",
"upstream",
",",
"downstream",
"=",
"self",
".",
"transmission_rate",
"return",
"(",
"fritztools",
".",
"format_num",
"(",
"upstream",
")",
",",
"fritztools",
".",
"format_num",
"(",
"downstream",
")",
")"... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzStatus.max_bit_rate | Returns a tuple with the maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec. | fritzconnection/fritzstatus.py | def max_bit_rate(self):
"""
Returns a tuple with the maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec.
"""
status = self.fc.call_action('WANCommonInterfaceConfig',
'GetCommonLinkProperties')
... | def max_bit_rate(self):
"""
Returns a tuple with the maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec.
"""
status = self.fc.call_action('WANCommonInterfaceConfig',
'GetCommonLinkProperties')
... | [
"Returns",
"a",
"tuple",
"with",
"the",
"maximun",
"upstream",
"-",
"and",
"downstream",
"-",
"rate",
"of",
"the",
"given",
"connection",
".",
"The",
"rate",
"is",
"given",
"in",
"bits",
"/",
"sec",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L127-L136 | [
"def",
"max_bit_rate",
"(",
"self",
")",
":",
"status",
"=",
"self",
".",
"fc",
".",
"call_action",
"(",
"'WANCommonInterfaceConfig'",
",",
"'GetCommonLinkProperties'",
")",
"downstream",
"=",
"status",
"[",
"'NewLayer1DownstreamMaxBitRate'",
"]",
"upstream",
"=",
... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzStatus.str_max_bit_rate | Returns a human readable maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec. | fritzconnection/fritzstatus.py | def str_max_bit_rate(self):
"""
Returns a human readable maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec.
"""
upstream, downstream = self.max_bit_rate
return (
fritztools.format_rate(upstream, unit='bits'),
... | def str_max_bit_rate(self):
"""
Returns a human readable maximun upstream- and downstream-rate
of the given connection. The rate is given in bits/sec.
"""
upstream, downstream = self.max_bit_rate
return (
fritztools.format_rate(upstream, unit='bits'),
... | [
"Returns",
"a",
"human",
"readable",
"maximun",
"upstream",
"-",
"and",
"downstream",
"-",
"rate",
"of",
"the",
"given",
"connection",
".",
"The",
"rate",
"is",
"given",
"in",
"bits",
"/",
"sec",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzstatus.py#L147-L156 | [
"def",
"str_max_bit_rate",
"(",
"self",
")",
":",
"upstream",
",",
"downstream",
"=",
"self",
".",
"max_bit_rate",
"return",
"(",
"fritztools",
".",
"format_rate",
"(",
"upstream",
",",
"unit",
"=",
"'bits'",
")",
",",
"fritztools",
".",
"format_rate",
"(",
... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzAction._body_builder | Helper method to construct the appropriate SOAP-body to call a
FritzBox-Service. | fritzconnection/fritzconnection.py | def _body_builder(self, kwargs):
"""
Helper method to construct the appropriate SOAP-body to call a
FritzBox-Service.
"""
p = {
'action_name': self.name,
'service_type': self.service_type,
'arguments': '',
}
if kwargs:
... | def _body_builder(self, kwargs):
"""
Helper method to construct the appropriate SOAP-body to call a
FritzBox-Service.
"""
p = {
'action_name': self.name,
'service_type': self.service_type,
'arguments': '',
}
if kwargs:
... | [
"Helper",
"method",
"to",
"construct",
"the",
"appropriate",
"SOAP",
"-",
"body",
"to",
"call",
"a",
"FritzBox",
"-",
"Service",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L94-L111 | [
"def",
"_body_builder",
"(",
"self",
",",
"kwargs",
")",
":",
"p",
"=",
"{",
"'action_name'",
":",
"self",
".",
"name",
",",
"'service_type'",
":",
"self",
".",
"service_type",
",",
"'arguments'",
":",
"''",
",",
"}",
"if",
"kwargs",
":",
"arguments",
... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzAction.execute | Calls the FritzBox action and returns a dictionary with the arguments. | fritzconnection/fritzconnection.py | def execute(self, **kwargs):
"""
Calls the FritzBox action and returns a dictionary with the arguments.
"""
headers = self.header.copy()
headers['soapaction'] = '%s#%s' % (self.service_type, self.name)
data = self.envelope.strip() % self._body_builder(kwargs)
url ... | def execute(self, **kwargs):
"""
Calls the FritzBox action and returns a dictionary with the arguments.
"""
headers = self.header.copy()
headers['soapaction'] = '%s#%s' % (self.service_type, self.name)
data = self.envelope.strip() % self._body_builder(kwargs)
url ... | [
"Calls",
"the",
"FritzBox",
"action",
"and",
"returns",
"a",
"dictionary",
"with",
"the",
"arguments",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L113-L127 | [
"def",
"execute",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"self",
".",
"header",
".",
"copy",
"(",
")",
"headers",
"[",
"'soapaction'",
"]",
"=",
"'%s#%s'",
"%",
"(",
"self",
".",
"service_type",
",",
"self",
".",
"name",
")... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzAction.parse_response | Evaluates the action-call response from a FritzBox.
The response is a xml byte-string.
Returns a dictionary with the received arguments-value pairs.
The values are converted according to the given data_types.
TODO: boolean and signed integers data-types from tr64 responses | fritzconnection/fritzconnection.py | def parse_response(self, response):
"""
Evaluates the action-call response from a FritzBox.
The response is a xml byte-string.
Returns a dictionary with the received arguments-value pairs.
The values are converted according to the given data_types.
TODO: boolean and signe... | def parse_response(self, response):
"""
Evaluates the action-call response from a FritzBox.
The response is a xml byte-string.
Returns a dictionary with the received arguments-value pairs.
The values are converted according to the given data_types.
TODO: boolean and signe... | [
"Evaluates",
"the",
"action",
"-",
"call",
"response",
"from",
"a",
"FritzBox",
".",
"The",
"response",
"is",
"a",
"xml",
"byte",
"-",
"string",
".",
"Returns",
"a",
"dictionary",
"with",
"the",
"received",
"arguments",
"-",
"value",
"pairs",
".",
"The",
... | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L129-L153 | [
"def",
"parse_response",
"(",
"self",
",",
"response",
")",
":",
"result",
"=",
"{",
"}",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"response",
")",
"for",
"argument",
"in",
"self",
".",
"arguments",
".",
"values",
"(",
")",
":",
"try",
":",
"val... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzDescParser.get_modelname | Returns the FritzBox model name. | fritzconnection/fritzconnection.py | def get_modelname(self):
"""Returns the FritzBox model name."""
xpath = '%s/%s' % (self.nodename('device'), self.nodename('modelName'))
return self.root.find(xpath).text | def get_modelname(self):
"""Returns the FritzBox model name."""
xpath = '%s/%s' % (self.nodename('device'), self.nodename('modelName'))
return self.root.find(xpath).text | [
"Returns",
"the",
"FritzBox",
"model",
"name",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L202-L205 | [
"def",
"get_modelname",
"(",
"self",
")",
":",
"xpath",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"nodename",
"(",
"'device'",
")",
",",
"self",
".",
"nodename",
"(",
"'modelName'",
")",
")",
"return",
"self",
".",
"root",
".",
"find",
"(",
"xpath",
")"... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzDescParser.get_services | Returns a list of FritzService-objects. | fritzconnection/fritzconnection.py | def get_services(self):
"""Returns a list of FritzService-objects."""
result = []
nodes = self.root.iterfind(
'.//ns:service', namespaces={'ns': self.namespace})
for node in nodes:
result.append(FritzService(
node.find(self.nodename('serviceType'))... | def get_services(self):
"""Returns a list of FritzService-objects."""
result = []
nodes = self.root.iterfind(
'.//ns:service', namespaces={'ns': self.namespace})
for node in nodes:
result.append(FritzService(
node.find(self.nodename('serviceType'))... | [
"Returns",
"a",
"list",
"of",
"FritzService",
"-",
"objects",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L207-L217 | [
"def",
"get_services",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"nodes",
"=",
"self",
".",
"root",
".",
"iterfind",
"(",
"'.//ns:service'",
",",
"namespaces",
"=",
"{",
"'ns'",
":",
"self",
".",
"namespace",
"}",
")",
"for",
"node",
"in",
"nod... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzSCDPParser._read_state_variables | Reads the stateVariable information from the xml-file.
The information we like to extract are name and dataType so we
can assign them later on to FritzActionArgument-instances.
Returns a dictionary: key:value = name:dataType | fritzconnection/fritzconnection.py | def _read_state_variables(self):
"""
Reads the stateVariable information from the xml-file.
The information we like to extract are name and dataType so we
can assign them later on to FritzActionArgument-instances.
Returns a dictionary: key:value = name:dataType
"""
... | def _read_state_variables(self):
"""
Reads the stateVariable information from the xml-file.
The information we like to extract are name and dataType so we
can assign them later on to FritzActionArgument-instances.
Returns a dictionary: key:value = name:dataType
"""
... | [
"Reads",
"the",
"stateVariable",
"information",
"from",
"the",
"xml",
"-",
"file",
".",
"The",
"information",
"we",
"like",
"to",
"extract",
"are",
"name",
"and",
"dataType",
"so",
"we",
"can",
"assign",
"them",
"later",
"on",
"to",
"FritzActionArgument",
"-... | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L240-L252 | [
"def",
"_read_state_variables",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"root",
".",
"iterfind",
"(",
"'.//ns:stateVariable'",
",",
"namespaces",
"=",
"{",
"'ns'",
":",
"self",
".",
"namespace",
"}",
")",
"for",
"node",
"in",
"nodes",
":",
"key... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzSCDPParser.get_actions | Returns a list of FritzAction instances. | fritzconnection/fritzconnection.py | def get_actions(self):
"""Returns a list of FritzAction instances."""
self._read_state_variables()
actions = []
nodes = self.root.iterfind(
'.//ns:action', namespaces={'ns': self.namespace})
for node in nodes:
action = FritzAction(self.service.service_type... | def get_actions(self):
"""Returns a list of FritzAction instances."""
self._read_state_variables()
actions = []
nodes = self.root.iterfind(
'.//ns:action', namespaces={'ns': self.namespace})
for node in nodes:
action = FritzAction(self.service.service_type... | [
"Returns",
"a",
"list",
"of",
"FritzAction",
"instances",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L254-L266 | [
"def",
"get_actions",
"(",
"self",
")",
":",
"self",
".",
"_read_state_variables",
"(",
")",
"actions",
"=",
"[",
"]",
"nodes",
"=",
"self",
".",
"root",
".",
"iterfind",
"(",
"'.//ns:action'",
",",
"namespaces",
"=",
"{",
"'ns'",
":",
"self",
".",
"na... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzSCDPParser._get_arguments | Returns a dictionary of arguments for the given action_node. | fritzconnection/fritzconnection.py | def _get_arguments(self, action_node):
"""
Returns a dictionary of arguments for the given action_node.
"""
arguments = {}
argument_nodes = action_node.iterfind(
r'./ns:argumentList/ns:argument', namespaces={'ns': self.namespace})
for argument_node in argument... | def _get_arguments(self, action_node):
"""
Returns a dictionary of arguments for the given action_node.
"""
arguments = {}
argument_nodes = action_node.iterfind(
r'./ns:argumentList/ns:argument', namespaces={'ns': self.namespace})
for argument_node in argument... | [
"Returns",
"a",
"dictionary",
"of",
"arguments",
"for",
"the",
"given",
"action_node",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L268-L278 | [
"def",
"_get_arguments",
"(",
"self",
",",
"action_node",
")",
":",
"arguments",
"=",
"{",
"}",
"argument_nodes",
"=",
"action_node",
".",
"iterfind",
"(",
"r'./ns:argumentList/ns:argument'",
",",
"namespaces",
"=",
"{",
"'ns'",
":",
"self",
".",
"namespace",
... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzSCDPParser._get_argument | Returns a FritzActionArgument instance for the given argument_node. | fritzconnection/fritzconnection.py | def _get_argument(self, argument_node):
"""
Returns a FritzActionArgument instance for the given argument_node.
"""
argument = FritzActionArgument()
argument.name = argument_node.find(self.nodename('name')).text
argument.direction = argument_node.find(self.nodename('direc... | def _get_argument(self, argument_node):
"""
Returns a FritzActionArgument instance for the given argument_node.
"""
argument = FritzActionArgument()
argument.name = argument_node.find(self.nodename('name')).text
argument.direction = argument_node.find(self.nodename('direc... | [
"Returns",
"a",
"FritzActionArgument",
"instance",
"for",
"the",
"given",
"argument_node",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L280-L290 | [
"def",
"_get_argument",
"(",
"self",
",",
"argument_node",
")",
":",
"argument",
"=",
"FritzActionArgument",
"(",
")",
"argument",
".",
"name",
"=",
"argument_node",
".",
"find",
"(",
"self",
".",
"nodename",
"(",
"'name'",
")",
")",
".",
"text",
"argument... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzConnection._read_descriptions | Read and evaluate the igddesc.xml file
and the tr64desc.xml file if a password is given. | fritzconnection/fritzconnection.py | def _read_descriptions(self, password):
"""
Read and evaluate the igddesc.xml file
and the tr64desc.xml file if a password is given.
"""
descfiles = [FRITZ_IGD_DESC_FILE]
if password:
descfiles.append(FRITZ_TR64_DESC_FILE)
for descfile in descfiles:
... | def _read_descriptions(self, password):
"""
Read and evaluate the igddesc.xml file
and the tr64desc.xml file if a password is given.
"""
descfiles = [FRITZ_IGD_DESC_FILE]
if password:
descfiles.append(FRITZ_TR64_DESC_FILE)
for descfile in descfiles:
... | [
"Read",
"and",
"evaluate",
"the",
"igddesc",
".",
"xml",
"file",
"and",
"the",
"tr64desc",
".",
"xml",
"file",
"if",
"a",
"password",
"is",
"given",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L315-L328 | [
"def",
"_read_descriptions",
"(",
"self",
",",
"password",
")",
":",
"descfiles",
"=",
"[",
"FRITZ_IGD_DESC_FILE",
"]",
"if",
"password",
":",
"descfiles",
".",
"append",
"(",
"FRITZ_TR64_DESC_FILE",
")",
"for",
"descfile",
"in",
"descfiles",
":",
"parser",
"=... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzConnection._read_services | Get actions from services. | fritzconnection/fritzconnection.py | def _read_services(self, services):
"""Get actions from services."""
for service in services:
parser = FritzSCDPParser(self.address, self.port, service)
actions = parser.get_actions()
service.actions = {action.name: action for action in actions}
self.servi... | def _read_services(self, services):
"""Get actions from services."""
for service in services:
parser = FritzSCDPParser(self.address, self.port, service)
actions = parser.get_actions()
service.actions = {action.name: action for action in actions}
self.servi... | [
"Get",
"actions",
"from",
"services",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L330-L336 | [
"def",
"_read_services",
"(",
"self",
",",
"services",
")",
":",
"for",
"service",
"in",
"services",
":",
"parser",
"=",
"FritzSCDPParser",
"(",
"self",
".",
"address",
",",
"self",
".",
"port",
",",
"service",
")",
"actions",
"=",
"parser",
".",
"get_ac... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzConnection.actionnames | Returns a alphabetical sorted list of tuples with all known
service- and action-names. | fritzconnection/fritzconnection.py | def actionnames(self):
"""
Returns a alphabetical sorted list of tuples with all known
service- and action-names.
"""
actions = []
for service_name in sorted(self.services.keys()):
action_names = self.services[service_name].actions.keys()
for actio... | def actionnames(self):
"""
Returns a alphabetical sorted list of tuples with all known
service- and action-names.
"""
actions = []
for service_name in sorted(self.services.keys()):
action_names = self.services[service_name].actions.keys()
for actio... | [
"Returns",
"a",
"alphabetical",
"sorted",
"list",
"of",
"tuples",
"with",
"all",
"known",
"service",
"-",
"and",
"action",
"-",
"names",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L339-L349 | [
"def",
"actionnames",
"(",
"self",
")",
":",
"actions",
"=",
"[",
"]",
"for",
"service_name",
"in",
"sorted",
"(",
"self",
".",
"services",
".",
"keys",
"(",
")",
")",
":",
"action_names",
"=",
"self",
".",
"services",
"[",
"service_name",
"]",
".",
... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzConnection.get_action_arguments | Returns a list of tuples with all known arguments for the given
service- and action-name combination. The tuples contain the
argument-name, direction and data_type. | fritzconnection/fritzconnection.py | def get_action_arguments(self, service_name, action_name):
"""
Returns a list of tuples with all known arguments for the given
service- and action-name combination. The tuples contain the
argument-name, direction and data_type.
"""
return self.services[service_name].actio... | def get_action_arguments(self, service_name, action_name):
"""
Returns a list of tuples with all known arguments for the given
service- and action-name combination. The tuples contain the
argument-name, direction and data_type.
"""
return self.services[service_name].actio... | [
"Returns",
"a",
"list",
"of",
"tuples",
"with",
"all",
"known",
"arguments",
"for",
"the",
"given",
"service",
"-",
"and",
"action",
"-",
"name",
"combination",
".",
"The",
"tuples",
"contain",
"the",
"argument",
"-",
"name",
"direction",
"and",
"data_type",... | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L351-L357 | [
"def",
"get_action_arguments",
"(",
"self",
",",
"service_name",
",",
"action_name",
")",
":",
"return",
"self",
".",
"services",
"[",
"service_name",
"]",
".",
"actions",
"[",
"action_name",
"]",
".",
"info"
] | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzConnection.call_action | Executes the given action. Raise a KeyError on unkown actions. | fritzconnection/fritzconnection.py | def call_action(self, service_name, action_name, **kwargs):
"""Executes the given action. Raise a KeyError on unkown actions."""
action = self.services[service_name].actions[action_name]
return action.execute(**kwargs) | def call_action(self, service_name, action_name, **kwargs):
"""Executes the given action. Raise a KeyError on unkown actions."""
action = self.services[service_name].actions[action_name]
return action.execute(**kwargs) | [
"Executes",
"the",
"given",
"action",
".",
"Raise",
"a",
"KeyError",
"on",
"unkown",
"actions",
"."
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L359-L362 | [
"def",
"call_action",
"(",
"self",
",",
"service_name",
",",
"action_name",
",",
"*",
"*",
"kwargs",
")",
":",
"action",
"=",
"self",
".",
"services",
"[",
"service_name",
"]",
".",
"actions",
"[",
"action_name",
"]",
"return",
"action",
".",
"execute",
... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | FritzHosts.get_hosts_info | Returns a list of dicts with information about the known hosts.
The dict-keys are: 'ip', 'name', 'mac', 'status' | fritzconnection/fritzhosts.py | def get_hosts_info(self):
"""
Returns a list of dicts with information about the known hosts.
The dict-keys are: 'ip', 'name', 'mac', 'status'
"""
result = []
index = 0
while index < self.host_numbers:
host = self.get_generic_host_entry(index)
... | def get_hosts_info(self):
"""
Returns a list of dicts with information about the known hosts.
The dict-keys are: 'ip', 'name', 'mac', 'status'
"""
result = []
index = 0
while index < self.host_numbers:
host = self.get_generic_host_entry(index)
... | [
"Returns",
"a",
"list",
"of",
"dicts",
"with",
"information",
"about",
"the",
"known",
"hosts",
".",
"The",
"dict",
"-",
"keys",
"are",
":",
"ip",
"name",
"mac",
"status"
] | kbr/fritzconnection | python | https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzhosts.py#L50-L65 | [
"def",
"get_hosts_info",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"index",
"=",
"0",
"while",
"index",
"<",
"self",
".",
"host_numbers",
":",
"host",
"=",
"self",
".",
"get_generic_host_entry",
"(",
"index",
")",
"result",
".",
"append",
"(",
"{... | b183f759ef19dd1652371e912d36cfe34f6639ac |
train | find_executable | Finds executable in PATH
Returns:
string or None | talkey/utils.py | def find_executable(executable):
'''
Finds executable in PATH
Returns:
string or None
'''
logger = logging.getLogger(__name__)
logger.debug("Checking executable '%s'...", executable)
executable_path = _find_executable(executable)
found = executable_path is not None
if found:... | def find_executable(executable):
'''
Finds executable in PATH
Returns:
string or None
'''
logger = logging.getLogger(__name__)
logger.debug("Checking executable '%s'...", executable)
executable_path = _find_executable(executable)
found = executable_path is not None
if found:... | [
"Finds",
"executable",
"in",
"PATH"
] | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/utils.py#L12-L27 | [
"def",
"find_executable",
"(",
"executable",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"Checking executable '%s'...\"",
",",
"executable",
")",
"executable_path",
"=",
"_find_executable",
"(",
"execu... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | check_network_connection | Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False | talkey/utils.py | def check_network_connection(server, port):
'''
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False
'''
logger = logging.getLogger(__name__)
logger.debug... | def check_network_connection(server, port):
'''
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False
'''
logger = logging.getLogger(__name__)
logger.debug... | [
"Checks",
"if",
"jasper",
"can",
"connect",
"a",
"network",
"server",
".",
"Arguments",
":",
"server",
"--",
"(",
"optional",
")",
"the",
"server",
"to",
"connect",
"with",
"(",
"Default",
":",
"www",
".",
"google",
".",
"com",
")",
"Returns",
":",
"Tr... | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/utils.py#L40-L63 | [
"def",
"check_network_connection",
"(",
"server",
",",
"port",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"Checking network connection to server '%s'...\"",
",",
"server",
")",
"try",
":",
"# see if w... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | check_python_import | Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False | talkey/utils.py | def check_python_import(package_or_module):
'''
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
'''
logger = logging.getLogger(__name__)
logger.debug("Checking python import '%s'...... | def check_python_import(package_or_module):
'''
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
'''
logger = logging.getLogger(__name__)
logger.debug("Checking python import '%s'...... | [
"Checks",
"if",
"a",
"python",
"package",
"or",
"module",
"is",
"importable",
".",
"Arguments",
":",
"package_or_module",
"--",
"the",
"package",
"or",
"module",
"name",
"to",
"check",
"Returns",
":",
"True",
"or",
"False"
] | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/utils.py#L66-L84 | [
"def",
"check_python_import",
"(",
"package_or_module",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"Checking python import '%s'...\"",
",",
"package_or_module",
")",
"loader",
"=",
"pkgutil",
".",
"ge... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | Axe.inject | Recursively inject aXe into all iframes and the top level document.
:param script_url: location of the axe-core script.
:type script_url: string | axe_selenium_python/axe.py | def inject(self):
"""
Recursively inject aXe into all iframes and the top level document.
:param script_url: location of the axe-core script.
:type script_url: string
"""
with open(self.script_url, "r", encoding="utf8") as f:
self.selenium.execute_script(f.re... | def inject(self):
"""
Recursively inject aXe into all iframes and the top level document.
:param script_url: location of the axe-core script.
:type script_url: string
"""
with open(self.script_url, "r", encoding="utf8") as f:
self.selenium.execute_script(f.re... | [
"Recursively",
"inject",
"aXe",
"into",
"all",
"iframes",
"and",
"the",
"top",
"level",
"document",
"."
] | mozilla-services/axe-selenium-python | python | https://github.com/mozilla-services/axe-selenium-python/blob/475c9f4eb771587aea73897bee356284d0361d77/axe_selenium_python/axe.py#L19-L27 | [
"def",
"inject",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"script_url",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf8\"",
")",
"as",
"f",
":",
"self",
".",
"selenium",
".",
"execute_script",
"(",
"f",
".",
"read",
"(",
")",
")"
] | 475c9f4eb771587aea73897bee356284d0361d77 |
train | Axe.run | Run axe against the current page.
:param context: which page part(s) to analyze and/or what to exclude.
:param options: dictionary of aXe options. | axe_selenium_python/axe.py | def run(self, context=None, options=None):
"""
Run axe against the current page.
:param context: which page part(s) to analyze and/or what to exclude.
:param options: dictionary of aXe options.
"""
template = (
"var callback = arguments[arguments.length - 1];... | def run(self, context=None, options=None):
"""
Run axe against the current page.
:param context: which page part(s) to analyze and/or what to exclude.
:param options: dictionary of aXe options.
"""
template = (
"var callback = arguments[arguments.length - 1];... | [
"Run",
"axe",
"against",
"the",
"current",
"page",
"."
] | mozilla-services/axe-selenium-python | python | https://github.com/mozilla-services/axe-selenium-python/blob/475c9f4eb771587aea73897bee356284d0361d77/axe_selenium_python/axe.py#L29-L54 | [
"def",
"run",
"(",
"self",
",",
"context",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"template",
"=",
"(",
"\"var callback = arguments[arguments.length - 1];\"",
"+",
"\"axe.run(%s).then(results => callback(results))\"",
")",
"args",
"=",
"\"\"",
"# If conte... | 475c9f4eb771587aea73897bee356284d0361d77 |
train | Axe.report | Return readable report of accessibility violations found.
:param violations: Dictionary of violations.
:type violations: dict
:return report: Readable report of violations.
:rtype: string | axe_selenium_python/axe.py | def report(self, violations):
"""
Return readable report of accessibility violations found.
:param violations: Dictionary of violations.
:type violations: dict
:return report: Readable report of violations.
:rtype: string
"""
string = ""
string +=... | def report(self, violations):
"""
Return readable report of accessibility violations found.
:param violations: Dictionary of violations.
:type violations: dict
:return report: Readable report of violations.
:rtype: string
"""
string = ""
string +=... | [
"Return",
"readable",
"report",
"of",
"accessibility",
"violations",
"found",
"."
] | mozilla-services/axe-selenium-python | python | https://github.com/mozilla-services/axe-selenium-python/blob/475c9f4eb771587aea73897bee356284d0361d77/axe_selenium_python/axe.py#L56-L94 | [
"def",
"report",
"(",
"self",
",",
"violations",
")",
":",
"string",
"=",
"\"\"",
"string",
"+=",
"\"Found \"",
"+",
"str",
"(",
"len",
"(",
"violations",
")",
")",
"+",
"\" accessibility violations:\"",
"for",
"violation",
"in",
"violations",
":",
"string",... | 475c9f4eb771587aea73897bee356284d0361d77 |
train | Axe.write_results | Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
:param output: JSON object. | axe_selenium_python/axe.py | def write_results(self, data, name=None):
"""
Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
:para... | def write_results(self, data, name=None):
"""
Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
:para... | [
"Write",
"JSON",
"to",
"file",
"with",
"the",
"specified",
"name",
"."
] | mozilla-services/axe-selenium-python | python | https://github.com/mozilla-services/axe-selenium-python/blob/475c9f4eb771587aea73897bee356284d0361d77/axe_selenium_python/axe.py#L96-L115 | [
"def",
"write_results",
"(",
"self",
",",
"data",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"name",
")",
"else",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os"... | 475c9f4eb771587aea73897bee356284d0361d77 |
train | create_engine | Creates an instance of an engine.
There is a two-stage instantiation process with engines.
1. ``options``:
The keyword options to instantiate the engine class
2. ``defaults``:
The default configuration for the engine (options often depends on instantiated TTS engine) | talkey/tts.py | def create_engine(engine, options=None, defaults=None):
'''
Creates an instance of an engine.
There is a two-stage instantiation process with engines.
1. ``options``:
The keyword options to instantiate the engine class
2. ``defaults``:
The default configuration for the engine (optio... | def create_engine(engine, options=None, defaults=None):
'''
Creates an instance of an engine.
There is a two-stage instantiation process with engines.
1. ``options``:
The keyword options to instantiate the engine class
2. ``defaults``:
The default configuration for the engine (optio... | [
"Creates",
"an",
"instance",
"of",
"an",
"engine",
".",
"There",
"is",
"a",
"two",
"-",
"stage",
"instantiation",
"process",
"with",
"engines",
"."
] | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/tts.py#L14-L31 | [
"def",
"create_engine",
"(",
"engine",
",",
"options",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"if",
"engine",
"not",
"in",
"_ENGINE_MAP",
".",
"keys",
"(",
")",
":",
"raise",
"TTSError",
"(",
"'Unknown engine %s'",
"%",
"engine",
")",
"opti... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | Talkey.classify | Classifies text by language. Uses preferred_languages weighting. | talkey/tts.py | def classify(self, txt):
'''
Classifies text by language. Uses preferred_languages weighting.
'''
ranks = []
for lang, score in langid.rank(txt):
if lang in self.preferred_languages:
score += self.preferred_factor
ranks.append((lang, score)... | def classify(self, txt):
'''
Classifies text by language. Uses preferred_languages weighting.
'''
ranks = []
for lang, score in langid.rank(txt):
if lang in self.preferred_languages:
score += self.preferred_factor
ranks.append((lang, score)... | [
"Classifies",
"text",
"by",
"language",
".",
"Uses",
"preferred_languages",
"weighting",
"."
] | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/tts.py#L105-L115 | [
"def",
"classify",
"(",
"self",
",",
"txt",
")",
":",
"ranks",
"=",
"[",
"]",
"for",
"lang",
",",
"score",
"in",
"langid",
".",
"rank",
"(",
"txt",
")",
":",
"if",
"lang",
"in",
"self",
".",
"preferred_languages",
":",
"score",
"+=",
"self",
".",
... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | Talkey.get_engine_for_lang | Determines the preferred engine/voice for a language. | talkey/tts.py | def get_engine_for_lang(self, lang):
'''
Determines the preferred engine/voice for a language.
'''
for eng in self.engines:
if lang in eng.languages.keys():
return eng
raise TTSError('Could not match language') | def get_engine_for_lang(self, lang):
'''
Determines the preferred engine/voice for a language.
'''
for eng in self.engines:
if lang in eng.languages.keys():
return eng
raise TTSError('Could not match language') | [
"Determines",
"the",
"preferred",
"engine",
"/",
"voice",
"for",
"a",
"language",
"."
] | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/tts.py#L117-L124 | [
"def",
"get_engine_for_lang",
"(",
"self",
",",
"lang",
")",
":",
"for",
"eng",
"in",
"self",
".",
"engines",
":",
"if",
"lang",
"in",
"eng",
".",
"languages",
".",
"keys",
"(",
")",
":",
"return",
"eng",
"raise",
"TTSError",
"(",
"'Could not match langu... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | Talkey.say | Says the text.
if ``lang`` is ``None``, then uses ``classify()`` to detect language. | talkey/tts.py | def say(self, txt, lang=None):
'''
Says the text.
if ``lang`` is ``None``, then uses ``classify()`` to detect language.
'''
lang = lang or self.classify(txt)
self.get_engine_for_lang(lang).say(txt, language=lang) | def say(self, txt, lang=None):
'''
Says the text.
if ``lang`` is ``None``, then uses ``classify()`` to detect language.
'''
lang = lang or self.classify(txt)
self.get_engine_for_lang(lang).say(txt, language=lang) | [
"Says",
"the",
"text",
"."
] | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/tts.py#L126-L133 | [
"def",
"say",
"(",
"self",
",",
"txt",
",",
"lang",
"=",
"None",
")",
":",
"lang",
"=",
"lang",
"or",
"self",
".",
"classify",
"(",
"txt",
")",
"self",
".",
"get_engine_for_lang",
"(",
"lang",
")",
".",
"say",
"(",
"txt",
",",
"language",
"=",
"l... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | AbstractTTSEngine.configure_default | Sets default configuration.
Raises TTSError on error. | talkey/base.py | def configure_default(self, **_options):
'''
Sets default configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options)
self.default_language = language
s... | def configure_default(self, **_options):
'''
Sets default configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options)
self.default_language = language
s... | [
"Sets",
"default",
"configuration",
"."
] | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/base.py#L206-L215 | [
"def",
"configure_default",
"(",
"self",
",",
"*",
"*",
"_options",
")",
":",
"language",
",",
"voice",
",",
"voiceinfo",
",",
"options",
"=",
"self",
".",
"_configure",
"(",
"*",
"*",
"_options",
")",
"self",
".",
"languages_options",
"[",
"language",
"... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | AbstractTTSEngine.configure | Sets language-specific configuration.
Raises TTSError on error. | talkey/base.py | def configure(self, **_options):
'''
Sets language-specific configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options) | def configure(self, **_options):
'''
Sets language-specific configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options) | [
"Sets",
"language",
"-",
"specific",
"configuration",
"."
] | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/base.py#L217-L224 | [
"def",
"configure",
"(",
"self",
",",
"*",
"*",
"_options",
")",
":",
"language",
",",
"voice",
",",
"voiceinfo",
",",
"options",
"=",
"self",
".",
"_configure",
"(",
"*",
"*",
"_options",
")",
"self",
".",
"languages_options",
"[",
"language",
"]",
"=... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | AbstractTTSEngine.say | Says the phrase, optionally allows to select/override any voice options. | talkey/base.py | def say(self, phrase, **_options):
'''
Says the phrase, optionally allows to select/override any voice options.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self._logger.debug("Saying '%s' with '%s'", phrase, self.SLUG)
self._say(phrase, language,... | def say(self, phrase, **_options):
'''
Says the phrase, optionally allows to select/override any voice options.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self._logger.debug("Saying '%s' with '%s'", phrase, self.SLUG)
self._say(phrase, language,... | [
"Says",
"the",
"phrase",
"optionally",
"allows",
"to",
"select",
"/",
"override",
"any",
"voice",
"options",
"."
] | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/base.py#L226-L232 | [
"def",
"say",
"(",
"self",
",",
"phrase",
",",
"*",
"*",
"_options",
")",
":",
"language",
",",
"voice",
",",
"voiceinfo",
",",
"options",
"=",
"self",
".",
"_configure",
"(",
"*",
"*",
"_options",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"\... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | AbstractTTSEngine.play | Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV. | talkey/base.py | def play(self, filename, translate=False): # pragma: no cover
'''
Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV.
'''
# FIXME: Use platform-independent an... | def play(self, filename, translate=False): # pragma: no cover
'''
Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV.
'''
# FIXME: Use platform-independent an... | [
"Plays",
"the",
"sounds",
"."
] | grigi/talkey | python | https://github.com/grigi/talkey/blob/5d2d4a1f7001744c4fd9a79a883a3f2001522329/talkey/base.py#L234-L264 | [
"def",
"play",
"(",
"self",
",",
"filename",
",",
"translate",
"=",
"False",
")",
":",
"# pragma: no cover",
"# FIXME: Use platform-independent and async audio-output here",
"# PyAudio looks most promising, too bad about:",
"# --allow-external PyAudio --allow-unverified PyAudio",
"i... | 5d2d4a1f7001744c4fd9a79a883a3f2001522329 |
train | getCollectDServer | Get the appropriate collectd server (multi processed or not) | bucky/collectd.py | def getCollectDServer(queue, cfg):
"""Get the appropriate collectd server (multi processed or not)"""
server = CollectDServerMP if cfg.collectd_workers > 1 else CollectDServer
return server(queue, cfg) | def getCollectDServer(queue, cfg):
"""Get the appropriate collectd server (multi processed or not)"""
server = CollectDServerMP if cfg.collectd_workers > 1 else CollectDServer
return server(queue, cfg) | [
"Get",
"the",
"appropriate",
"collectd",
"server",
"(",
"multi",
"processed",
"or",
"not",
")"
] | trbs/bucky | python | https://github.com/trbs/bucky/blob/ae4c696be46cda977cb5f27c31420985ef1cc0ba/bucky/collectd.py#L652-L655 | [
"def",
"getCollectDServer",
"(",
"queue",
",",
"cfg",
")",
":",
"server",
"=",
"CollectDServerMP",
"if",
"cfg",
".",
"collectd_workers",
">",
"1",
"else",
"CollectDServer",
"return",
"server",
"(",
"queue",
",",
"cfg",
")"
] | ae4c696be46cda977cb5f27c31420985ef1cc0ba |
train | CollectDCrypto._hashes_match | Constant time comparison of bytes for py3, strings for py2 | bucky/collectd.py | def _hashes_match(self, a, b):
"""Constant time comparison of bytes for py3, strings for py2"""
if len(a) != len(b):
return False
diff = 0
if six.PY2:
a = bytearray(a)
b = bytearray(b)
for x, y in zip(a, b):
diff |= x ^ y
re... | def _hashes_match(self, a, b):
"""Constant time comparison of bytes for py3, strings for py2"""
if len(a) != len(b):
return False
diff = 0
if six.PY2:
a = bytearray(a)
b = bytearray(b)
for x, y in zip(a, b):
diff |= x ^ y
re... | [
"Constant",
"time",
"comparison",
"of",
"bytes",
"for",
"py3",
"strings",
"for",
"py2"
] | trbs/bucky | python | https://github.com/trbs/bucky/blob/ae4c696be46cda977cb5f27c31420985ef1cc0ba/bucky/collectd.py#L369-L379 | [
"def",
"_hashes_match",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"return",
"False",
"diff",
"=",
"0",
"if",
"six",
".",
"PY2",
":",
"a",
"=",
"bytearray",
"(",
"a",
")",
"b",
"=... | ae4c696be46cda977cb5f27c31420985ef1cc0ba |
train | load_sites | Load metadata for all sites in given basin codes. | climata/bin/acis_sites.py | def load_sites(*basin_ids):
"""
Load metadata for all sites in given basin codes.
"""
# Resolve basin ids to HUC8s if needed
basins = []
for basin in basin_ids:
if basin.isdigit() and len(basin) == 8:
basins.append(basin)
else:
from climata.huc8 import ge... | def load_sites(*basin_ids):
"""
Load metadata for all sites in given basin codes.
"""
# Resolve basin ids to HUC8s if needed
basins = []
for basin in basin_ids:
if basin.isdigit() and len(basin) == 8:
basins.append(basin)
else:
from climata.huc8 import ge... | [
"Load",
"metadata",
"for",
"all",
"sites",
"in",
"given",
"basin",
"codes",
"."
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/bin/acis_sites.py#L16-L118 | [
"def",
"load_sites",
"(",
"*",
"basin_ids",
")",
":",
"# Resolve basin ids to HUC8s if needed",
"basins",
"=",
"[",
"]",
"for",
"basin",
"in",
"basin_ids",
":",
"if",
"basin",
".",
"isdigit",
"(",
")",
"and",
"len",
"(",
"basin",
")",
"==",
"8",
":",
"ba... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | get_huc8 | Return all HUC8s matching the given prefix (e.g. 1801) or basin name
(e.g. Klamath) | climata/huc8/__init__.py | def get_huc8(prefix):
"""
Return all HUC8s matching the given prefix (e.g. 1801) or basin name
(e.g. Klamath)
"""
if not prefix.isdigit():
# Look up hucs by name
name = prefix
prefix = None
for row in hucs:
if row.basin.lower() == name.lower():
... | def get_huc8(prefix):
"""
Return all HUC8s matching the given prefix (e.g. 1801) or basin name
(e.g. Klamath)
"""
if not prefix.isdigit():
# Look up hucs by name
name = prefix
prefix = None
for row in hucs:
if row.basin.lower() == name.lower():
... | [
"Return",
"all",
"HUC8s",
"matching",
"the",
"given",
"prefix",
"(",
"e",
".",
"g",
".",
"1801",
")",
"or",
"basin",
"name",
"(",
"e",
".",
"g",
".",
"Klamath",
")"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/huc8/__init__.py#L23-L46 | [
"def",
"get_huc8",
"(",
"prefix",
")",
":",
"if",
"not",
"prefix",
".",
"isdigit",
"(",
")",
":",
"# Look up hucs by name",
"name",
"=",
"prefix",
"prefix",
"=",
"None",
"for",
"row",
"in",
"hucs",
":",
"if",
"row",
".",
"basin",
".",
"lower",
"(",
"... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | StationMetaIO.parse | Convert ACIS 'll' value into separate latitude and longitude. | climata/acis/__init__.py | def parse(self):
"""
Convert ACIS 'll' value into separate latitude and longitude.
"""
super(AcisIO, self).parse()
# This is more of a "mapping" step than a "parsing" step, but mappers
# only allow one-to-one mapping from input fields to output fields.
for row in... | def parse(self):
"""
Convert ACIS 'll' value into separate latitude and longitude.
"""
super(AcisIO, self).parse()
# This is more of a "mapping" step than a "parsing" step, but mappers
# only allow one-to-one mapping from input fields to output fields.
for row in... | [
"Convert",
"ACIS",
"ll",
"value",
"into",
"separate",
"latitude",
"and",
"longitude",
"."
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L80-L93 | [
"def",
"parse",
"(",
"self",
")",
":",
"super",
"(",
"AcisIO",
",",
"self",
")",
".",
"parse",
"(",
")",
"# This is more of a \"mapping\" step than a \"parsing\" step, but mappers",
"# only allow one-to-one mapping from input fields to output fields.",
"for",
"row",
"in",
"... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | StationMetaIO.map_value | Clean up some values returned from the web service.
(overrides wq.io.mappers.BaseMapper) | climata/acis/__init__.py | def map_value(self, field, value):
"""
Clean up some values returned from the web service.
(overrides wq.io.mappers.BaseMapper)
"""
if field == 'sids':
# Site identifiers are returned as "[id] [auth_id]";
# Map to auth name for easier usability
... | def map_value(self, field, value):
"""
Clean up some values returned from the web service.
(overrides wq.io.mappers.BaseMapper)
"""
if field == 'sids':
# Site identifiers are returned as "[id] [auth_id]";
# Map to auth name for easier usability
... | [
"Clean",
"up",
"some",
"values",
"returned",
"from",
"the",
"web",
"service",
".",
"(",
"overrides",
"wq",
".",
"io",
".",
"mappers",
".",
"BaseMapper",
")"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L95-L124 | [
"def",
"map_value",
"(",
"self",
",",
"field",
",",
"value",
")",
":",
"if",
"field",
"==",
"'sids'",
":",
"# Site identifiers are returned as \"[id] [auth_id]\";",
"# Map to auth name for easier usability",
"ids",
"=",
"{",
"}",
"for",
"idinfo",
"in",
"value",
":",... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | StationDataIO.get_field_names | ACIS web service returns "meta" and "data" for each station;
Use meta attributes as field names | climata/acis/__init__.py | def get_field_names(self):
"""
ACIS web service returns "meta" and "data" for each station;
Use meta attributes as field names
"""
field_names = super(StationDataIO, self).get_field_names()
if set(field_names) == set(['meta', 'data']):
meta_fields = list(self.... | def get_field_names(self):
"""
ACIS web service returns "meta" and "data" for each station;
Use meta attributes as field names
"""
field_names = super(StationDataIO, self).get_field_names()
if set(field_names) == set(['meta', 'data']):
meta_fields = list(self.... | [
"ACIS",
"web",
"service",
"returns",
"meta",
"and",
"data",
"for",
"each",
"station",
";",
"Use",
"meta",
"attributes",
"as",
"field",
"names"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L147-L158 | [
"def",
"get_field_names",
"(",
"self",
")",
":",
"field_names",
"=",
"super",
"(",
"StationDataIO",
",",
"self",
")",
".",
"get_field_names",
"(",
")",
"if",
"set",
"(",
"field_names",
")",
"==",
"set",
"(",
"[",
"'meta'",
",",
"'data'",
"]",
")",
":",... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | StationDataIO.usable_item | ACIS web service returns "meta" and "data" for each station; use meta
attributes as item values, and add an IO for iterating over "data" | climata/acis/__init__.py | def usable_item(self, data):
"""
ACIS web service returns "meta" and "data" for each station; use meta
attributes as item values, and add an IO for iterating over "data"
"""
# Use metadata as item
item = data['meta']
# Add nested IO for data
elems, elems... | def usable_item(self, data):
"""
ACIS web service returns "meta" and "data" for each station; use meta
attributes as item values, and add an IO for iterating over "data"
"""
# Use metadata as item
item = data['meta']
# Add nested IO for data
elems, elems... | [
"ACIS",
"web",
"service",
"returns",
"meta",
"and",
"data",
"for",
"each",
"station",
";",
"use",
"meta",
"attributes",
"as",
"item",
"values",
"and",
"add",
"an",
"IO",
"for",
"iterating",
"over",
"data"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L175-L199 | [
"def",
"usable_item",
"(",
"self",
",",
"data",
")",
":",
"# Use metadata as item",
"item",
"=",
"data",
"[",
"'meta'",
"]",
"# Add nested IO for data",
"elems",
",",
"elems_is_complex",
"=",
"self",
".",
"getlist",
"(",
"'parameter'",
")",
"if",
"elems_is_compl... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | DataIO.load_data | MultiStnData data results are arrays without explicit dates;
Infer time series based on start date. | climata/acis/__init__.py | def load_data(self, data):
"""
MultiStnData data results are arrays without explicit dates;
Infer time series based on start date.
"""
dates = fill_date_range(self.start_date, self.end_date)
for row, date in zip(data, dates):
data = {'date': date}
... | def load_data(self, data):
"""
MultiStnData data results are arrays without explicit dates;
Infer time series based on start date.
"""
dates = fill_date_range(self.start_date, self.end_date)
for row, date in zip(data, dates):
data = {'date': date}
... | [
"MultiStnData",
"data",
"results",
"are",
"arrays",
"without",
"explicit",
"dates",
";",
"Infer",
"time",
"series",
"based",
"on",
"start",
"date",
"."
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L216-L243 | [
"def",
"load_data",
"(",
"self",
",",
"data",
")",
":",
"dates",
"=",
"fill_date_range",
"(",
"self",
".",
"start_date",
",",
"self",
".",
"end_date",
")",
"for",
"row",
",",
"date",
"in",
"zip",
"(",
"data",
",",
"dates",
")",
":",
"data",
"=",
"{... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | DataIO.get_field_names | Different field names depending on self.add setting (see load_data)
For BaseIO | climata/acis/__init__.py | def get_field_names(self):
"""
Different field names depending on self.add setting (see load_data)
For BaseIO
"""
if self.add:
return ['date', 'elem', 'value'] + [flag for flag in self.add]
else:
field_names = ['date']
for elem in self.... | def get_field_names(self):
"""
Different field names depending on self.add setting (see load_data)
For BaseIO
"""
if self.add:
return ['date', 'elem', 'value'] + [flag for flag in self.add]
else:
field_names = ['date']
for elem in self.... | [
"Different",
"field",
"names",
"depending",
"on",
"self",
".",
"add",
"setting",
"(",
"see",
"load_data",
")",
"For",
"BaseIO"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L250-L264 | [
"def",
"get_field_names",
"(",
"self",
")",
":",
"if",
"self",
".",
"add",
":",
"return",
"[",
"'date'",
",",
"'elem'",
",",
"'value'",
"]",
"+",
"[",
"flag",
"for",
"flag",
"in",
"self",
".",
"add",
"]",
"else",
":",
"field_names",
"=",
"[",
"'dat... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | fill_date_range | Function accepts start date, end date, and format (if dates are strings)
and returns a list of Python dates. | climata/base.py | def fill_date_range(start_date, end_date, date_format=None):
"""
Function accepts start date, end date, and format (if dates are strings)
and returns a list of Python dates.
"""
if date_format:
start_date = datetime.strptime(start_date, date_format).date()
end_date = datetime.strpti... | def fill_date_range(start_date, end_date, date_format=None):
"""
Function accepts start date, end date, and format (if dates are strings)
and returns a list of Python dates.
"""
if date_format:
start_date = datetime.strptime(start_date, date_format).date()
end_date = datetime.strpti... | [
"Function",
"accepts",
"start",
"date",
"end",
"date",
"and",
"format",
"(",
"if",
"dates",
"are",
"strings",
")",
"and",
"returns",
"a",
"list",
"of",
"Python",
"dates",
"."
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L252-L265 | [
"def",
"fill_date_range",
"(",
"start_date",
",",
"end_date",
",",
"date_format",
"=",
"None",
")",
":",
"if",
"date_format",
":",
"start_date",
"=",
"datetime",
".",
"strptime",
"(",
"start_date",
",",
"date_format",
")",
".",
"date",
"(",
")",
"end_date",
... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | FilterOpt.parse | Enforce rules and return parsed value | climata/base.py | def parse(self, value):
"""
Enforce rules and return parsed value
"""
if self.required and value is None:
raise ValueError("%s is required!" % self.name)
elif self.ignored and value is not None:
warn("%s is ignored for this class!" % self.name)
eli... | def parse(self, value):
"""
Enforce rules and return parsed value
"""
if self.required and value is None:
raise ValueError("%s is required!" % self.name)
elif self.ignored and value is not None:
warn("%s is ignored for this class!" % self.name)
eli... | [
"Enforce",
"rules",
"and",
"return",
"parsed",
"value"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L32-L49 | [
"def",
"parse",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"required",
"and",
"value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"%s is required!\"",
"%",
"self",
".",
"name",
")",
"elif",
"self",
".",
"ignored",
"and",
"value",
"is... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | DateOpt.parse | Parse date | climata/base.py | def parse(self, value):
"""
Parse date
"""
value = super(DateOpt, self).parse(value)
if value is None:
return None
if isinstance(value, str):
value = self.parse_date(value)
if isinstance(value, datetime) and self.date_only:
valu... | def parse(self, value):
"""
Parse date
"""
value = super(DateOpt, self).parse(value)
if value is None:
return None
if isinstance(value, str):
value = self.parse_date(value)
if isinstance(value, datetime) and self.date_only:
valu... | [
"Parse",
"date"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L58-L69 | [
"def",
"parse",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
"DateOpt",
",",
"self",
")",
".",
"parse",
"(",
"value",
")",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | WebserviceLoader.get_filter_options | List all filter options defined on class (and superclasses) | climata/base.py | def get_filter_options(cls):
"""
List all filter options defined on class (and superclasses)
"""
attr = '_filter_options_%s' % id(cls)
options = getattr(cls, attr, {})
if options:
return options
for key in dir(cls):
val = getattr(cls, key... | def get_filter_options(cls):
"""
List all filter options defined on class (and superclasses)
"""
attr = '_filter_options_%s' % id(cls)
options = getattr(cls, attr, {})
if options:
return options
for key in dir(cls):
val = getattr(cls, key... | [
"List",
"all",
"filter",
"options",
"defined",
"on",
"class",
"(",
"and",
"superclasses",
")"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L135-L151 | [
"def",
"get_filter_options",
"(",
"cls",
")",
":",
"attr",
"=",
"'_filter_options_%s'",
"%",
"id",
"(",
"cls",
")",
"options",
"=",
"getattr",
"(",
"cls",
",",
"attr",
",",
"{",
"}",
")",
"if",
"options",
":",
"return",
"options",
"for",
"key",
"in",
... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | WebserviceLoader.getlist | Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list) | climata/base.py | def getlist(self, name):
"""
Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list)
"""
value = self.getvalue(name)
complex = {}
def... | def getlist(self, name):
"""
Retrieve given property from class/instance, ensuring it is a list.
Also determine whether the list contains simple text/numeric values or
nested dictionaries (a "complex" list)
"""
value = self.getvalue(name)
complex = {}
def... | [
"Retrieve",
"given",
"property",
"from",
"class",
"/",
"instance",
"ensuring",
"it",
"is",
"a",
"list",
".",
"Also",
"determine",
"whether",
"the",
"list",
"contains",
"simple",
"text",
"/",
"numeric",
"values",
"or",
"nested",
"dictionaries",
"(",
"a",
"com... | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L163-L185 | [
"def",
"getlist",
"(",
"self",
",",
"name",
")",
":",
"value",
"=",
"self",
".",
"getvalue",
"(",
"name",
")",
"complex",
"=",
"{",
"}",
"def",
"str_value",
"(",
"val",
")",
":",
"# TODO: nonlocal complex",
"if",
"isinstance",
"(",
"val",
",",
"dict",
... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | WebserviceLoader.set_param | Set parameter key, noting whether list value is "complex" | climata/base.py | def set_param(self, into, name):
"""
Set parameter key, noting whether list value is "complex"
"""
value, complex = self.getlist(name)
if value is not None:
into[name] = value
return complex | def set_param(self, into, name):
"""
Set parameter key, noting whether list value is "complex"
"""
value, complex = self.getlist(name)
if value is not None:
into[name] = value
return complex | [
"Set",
"parameter",
"key",
"noting",
"whether",
"list",
"value",
"is",
"complex"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L187-L194 | [
"def",
"set_param",
"(",
"self",
",",
"into",
",",
"name",
")",
":",
"value",
",",
"complex",
"=",
"self",
".",
"getlist",
"(",
"name",
")",
"if",
"value",
"is",
"not",
"None",
":",
"into",
"[",
"name",
"]",
"=",
"value",
"return",
"complex"
] | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | WebserviceLoader.get_params | Get parameters for web service, noting whether any are "complex" | climata/base.py | def get_params(self):
"""
Get parameters for web service, noting whether any are "complex"
"""
params = {}
complex = False
for name, opt in self.filter_options.items():
if opt.ignored:
continue
if self.set_param(params, name):
... | def get_params(self):
"""
Get parameters for web service, noting whether any are "complex"
"""
params = {}
complex = False
for name, opt in self.filter_options.items():
if opt.ignored:
continue
if self.set_param(params, name):
... | [
"Get",
"parameters",
"for",
"web",
"service",
"noting",
"whether",
"any",
"are",
"complex"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L196-L208 | [
"def",
"get_params",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"complex",
"=",
"False",
"for",
"name",
",",
"opt",
"in",
"self",
".",
"filter_options",
".",
"items",
"(",
")",
":",
"if",
"opt",
".",
"ignored",
":",
"continue",
"if",
"self",
"... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | WebserviceLoader.params | URL parameters for wq.io.loaders.NetLoader | climata/base.py | def params(self):
"""
URL parameters for wq.io.loaders.NetLoader
"""
params, complex = self.get_params()
url_params = self.default_params.copy()
url_params.update(self.serialize_params(params, complex))
return url_params | def params(self):
"""
URL parameters for wq.io.loaders.NetLoader
"""
params, complex = self.get_params()
url_params = self.default_params.copy()
url_params.update(self.serialize_params(params, complex))
return url_params | [
"URL",
"parameters",
"for",
"wq",
".",
"io",
".",
"loaders",
".",
"NetLoader"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L211-L218 | [
"def",
"params",
"(",
"self",
")",
":",
"params",
",",
"complex",
"=",
"self",
".",
"get_params",
"(",
")",
"url_params",
"=",
"self",
".",
"default_params",
".",
"copy",
"(",
")",
"url_params",
".",
"update",
"(",
"self",
".",
"serialize_params",
"(",
... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | WebserviceLoader.serialize_params | Serialize parameter names and values to a dict ready for urlencode() | climata/base.py | def serialize_params(self, params, complex=False):
"""
Serialize parameter names and values to a dict ready for urlencode()
"""
if complex:
# See climata.acis for an example implementation
raise NotImplementedError("Cannot serialize %s!" % params)
else:
... | def serialize_params(self, params, complex=False):
"""
Serialize parameter names and values to a dict ready for urlencode()
"""
if complex:
# See climata.acis for an example implementation
raise NotImplementedError("Cannot serialize %s!" % params)
else:
... | [
"Serialize",
"parameter",
"names",
"and",
"values",
"to",
"a",
"dict",
"ready",
"for",
"urlencode",
"()"
] | heigeo/climata | python | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L220-L232 | [
"def",
"serialize_params",
"(",
"self",
",",
"params",
",",
"complex",
"=",
"False",
")",
":",
"if",
"complex",
":",
"# See climata.acis for an example implementation",
"raise",
"NotImplementedError",
"(",
"\"Cannot serialize %s!\"",
"%",
"params",
")",
"else",
":",
... | 2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd |
train | Distance.get_inches | convert the measurement to inches | ish_parser/Distance.py | def get_inches(self):
''' convert the measurement to inches '''
if self._obs_value in self.MISSING:
return 'MISSING'
if self._obs_units == self.MILLIMETERS:
return round(self.INCH_CONVERSION_FACTOR * self._obs_value, 4) | def get_inches(self):
''' convert the measurement to inches '''
if self._obs_value in self.MISSING:
return 'MISSING'
if self._obs_units == self.MILLIMETERS:
return round(self.INCH_CONVERSION_FACTOR * self._obs_value, 4) | [
"convert",
"the",
"measurement",
"to",
"inches"
] | haydenth/ish_parser | python | https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/Distance.py#L13-L18 | [
"def",
"get_inches",
"(",
"self",
")",
":",
"if",
"self",
".",
"_obs_value",
"in",
"self",
".",
"MISSING",
":",
"return",
"'MISSING'",
"if",
"self",
".",
"_obs_units",
"==",
"self",
".",
"MILLIMETERS",
":",
"return",
"round",
"(",
"self",
".",
"INCH_CONV... | 98fe3b3d0e5c672598be878d1715f214d5077869 |
train | ish_report.formatted | print a nicely formatted output of this report | ish_parser/ish_report.py | def formatted(self):
''' print a nicely formatted output of this report '''
return """
Weather Station: %s (%s, %s)
Elevation: %s m
Time: %s UTC
Air Temperature: %s C (%s F)
Wind Speed: %s m/s (%s mph)
Wind Direction: %s
Present Weather Obs: %s
Precipitation: %s
Cloud Coverage: %s oktas
Cloud Summation: %s
Sol... | def formatted(self):
''' print a nicely formatted output of this report '''
return """
Weather Station: %s (%s, %s)
Elevation: %s m
Time: %s UTC
Air Temperature: %s C (%s F)
Wind Speed: %s m/s (%s mph)
Wind Direction: %s
Present Weather Obs: %s
Precipitation: %s
Cloud Coverage: %s oktas
Cloud Summation: %s
Sol... | [
"print",
"a",
"nicely",
"formatted",
"output",
"of",
"this",
"report"
] | haydenth/ish_parser | python | https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_report.py#L296-L317 | [
"def",
"formatted",
"(",
"self",
")",
":",
"return",
"\"\"\"\nWeather Station: %s (%s, %s)\nElevation: %s m\nTime: %s UTC\nAir Temperature: %s C (%s F)\nWind Speed: %s m/s (%s mph)\nWind Direction: %s\nPresent Weather Obs: %s\nPrecipitation: %s\nCloud Coverage: %s oktas\nCloud Summation: %s\nSolar Irr... | 98fe3b3d0e5c672598be878d1715f214d5077869 |
train | ish_report.loads | load in a report (or set) from a string | ish_parser/ish_report.py | def loads(self, noaa_string):
''' load in a report (or set) from a string '''
self.raw = noaa_string
self.weather_station = noaa_string[4:10]
self.wban = noaa_string[10:15]
expected_length = int(noaa_string[0:4]) + self.PREAMBLE_LENGTH
actual_length = len(noaa_string)
if actual_length != exp... | def loads(self, noaa_string):
''' load in a report (or set) from a string '''
self.raw = noaa_string
self.weather_station = noaa_string[4:10]
self.wban = noaa_string[10:15]
expected_length = int(noaa_string[0:4]) + self.PREAMBLE_LENGTH
actual_length = len(noaa_string)
if actual_length != exp... | [
"load",
"in",
"a",
"report",
"(",
"or",
"set",
")",
"from",
"a",
"string"
] | haydenth/ish_parser | python | https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_report.py#L319-L399 | [
"def",
"loads",
"(",
"self",
",",
"noaa_string",
")",
":",
"self",
".",
"raw",
"=",
"noaa_string",
"self",
".",
"weather_station",
"=",
"noaa_string",
"[",
"4",
":",
"10",
"]",
"self",
".",
"wban",
"=",
"noaa_string",
"[",
"10",
":",
"15",
"]",
"expe... | 98fe3b3d0e5c672598be878d1715f214d5077869 |
train | ish_report._get_remarks_component | Parse the remarks into the _remarks dict | ish_parser/ish_report.py | def _get_remarks_component(self, string, initial_pos):
''' Parse the remarks into the _remarks dict '''
remarks_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH]
if remarks_code != 'REM':
raise ish_reportException("Parsing remarks. Expected REM but got %s." % (remarks_code,))
expecte... | def _get_remarks_component(self, string, initial_pos):
''' Parse the remarks into the _remarks dict '''
remarks_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH]
if remarks_code != 'REM':
raise ish_reportException("Parsing remarks. Expected REM but got %s." % (remarks_code,))
expecte... | [
"Parse",
"the",
"remarks",
"into",
"the",
"_remarks",
"dict"
] | haydenth/ish_parser | python | https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_report.py#L401-L419 | [
"def",
"_get_remarks_component",
"(",
"self",
",",
"string",
",",
"initial_pos",
")",
":",
"remarks_code",
"=",
"string",
"[",
"initial_pos",
":",
"initial_pos",
"+",
"self",
".",
"ADDR_CODE_LENGTH",
"]",
"if",
"remarks_code",
"!=",
"'REM'",
":",
"raise",
"ish... | 98fe3b3d0e5c672598be878d1715f214d5077869 |
train | ish_report._get_component | given a string and a position, return both an updated position and
either a Component Object or a String back to the caller | ish_parser/ish_report.py | def _get_component(self, string, initial_pos):
''' given a string and a position, return both an updated position and
either a Component Object or a String back to the caller '''
add_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH]
if add_code == 'REM':
raise ish_reportException... | def _get_component(self, string, initial_pos):
''' given a string and a position, return both an updated position and
either a Component Object or a String back to the caller '''
add_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH]
if add_code == 'REM':
raise ish_reportException... | [
"given",
"a",
"string",
"and",
"a",
"position",
"return",
"both",
"an",
"updated",
"position",
"and",
"either",
"a",
"Component",
"Object",
"or",
"a",
"String",
"back",
"to",
"the",
"caller"
] | haydenth/ish_parser | python | https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_report.py#L421-L456 | [
"def",
"_get_component",
"(",
"self",
",",
"string",
",",
"initial_pos",
")",
":",
"add_code",
"=",
"string",
"[",
"initial_pos",
":",
"initial_pos",
"+",
"self",
".",
"ADDR_CODE_LENGTH",
"]",
"if",
"add_code",
"==",
"'REM'",
":",
"raise",
"ish_reportException... | 98fe3b3d0e5c672598be878d1715f214d5077869 |
train | ish_parser.loads | load from a string | ish_parser/ish_parser.py | def loads(self, string):
''' load from a string '''
for line in string.split("\n"):
if len(line) < 10:
continue
try:
report = ish_report()
report.loads(line)
self._reports.append(report)
except BaseException as exp:
''' don't complain TOO much '''
... | def loads(self, string):
''' load from a string '''
for line in string.split("\n"):
if len(line) < 10:
continue
try:
report = ish_report()
report.loads(line)
self._reports.append(report)
except BaseException as exp:
''' don't complain TOO much '''
... | [
"load",
"from",
"a",
"string"
] | haydenth/ish_parser | python | https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_parser.py#L15-L27 | [
"def",
"loads",
"(",
"self",
",",
"string",
")",
":",
"for",
"line",
"in",
"string",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"len",
"(",
"line",
")",
"<",
"10",
":",
"continue",
"try",
":",
"report",
"=",
"ish_report",
"(",
")",
"report",
"... | 98fe3b3d0e5c672598be878d1715f214d5077869 |
train | ish_parser.get_observations | return only specific weather observations (FM types) and
ignore the summary of day reports | ish_parser/ish_parser.py | def get_observations(self):
''' return only specific weather observations (FM types) and
ignore the summary of day reports '''
return [rpt for rpt in self._reports if rpt.report_type in self.OBS_TYPES] | def get_observations(self):
''' return only specific weather observations (FM types) and
ignore the summary of day reports '''
return [rpt for rpt in self._reports if rpt.report_type in self.OBS_TYPES] | [
"return",
"only",
"specific",
"weather",
"observations",
"(",
"FM",
"types",
")",
"and",
"ignore",
"the",
"summary",
"of",
"day",
"reports"
] | haydenth/ish_parser | python | https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_parser.py#L33-L36 | [
"def",
"get_observations",
"(",
"self",
")",
":",
"return",
"[",
"rpt",
"for",
"rpt",
"in",
"self",
".",
"_reports",
"if",
"rpt",
".",
"report_type",
"in",
"self",
".",
"OBS_TYPES",
"]"
] | 98fe3b3d0e5c672598be878d1715f214d5077869 |
train | Speed.get_miles | convert the measurement to inches | ish_parser/Speed.py | def get_miles(self):
''' convert the measurement to inches '''
if self._obs_value in self.MISSING:
return 'MISSING'
if self._obs_units == self.METERSPERSECOND:
return round(2.23694 * self._obs_value, 4) | def get_miles(self):
''' convert the measurement to inches '''
if self._obs_value in self.MISSING:
return 'MISSING'
if self._obs_units == self.METERSPERSECOND:
return round(2.23694 * self._obs_value, 4) | [
"convert",
"the",
"measurement",
"to",
"inches"
] | haydenth/ish_parser | python | https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/Speed.py#L10-L15 | [
"def",
"get_miles",
"(",
"self",
")",
":",
"if",
"self",
".",
"_obs_value",
"in",
"self",
".",
"MISSING",
":",
"return",
"'MISSING'",
"if",
"self",
".",
"_obs_units",
"==",
"self",
".",
"METERSPERSECOND",
":",
"return",
"round",
"(",
"2.23694",
"*",
"sel... | 98fe3b3d0e5c672598be878d1715f214d5077869 |
train | TranslationGenerator.do_pot | Sync the template with the python code. | scripts/distribution/translation_generator.py | def do_pot(self):
"""
Sync the template with the python code.
"""
files_to_translate = []
log.debug("Collecting python sources for pot ...")
for source_path in self._source_paths:
for source_path in self._iter_suffix(path=source_path, suffix=".py"):
... | def do_pot(self):
"""
Sync the template with the python code.
"""
files_to_translate = []
log.debug("Collecting python sources for pot ...")
for source_path in self._source_paths:
for source_path in self._iter_suffix(path=source_path, suffix=".py"):
... | [
"Sync",
"the",
"template",
"with",
"the",
"python",
"code",
"."
] | subdownloader/subdownloader | python | https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/scripts/distribution/translation_generator.py#L47-L70 | [
"def",
"do_pot",
"(",
"self",
")",
":",
"files_to_translate",
"=",
"[",
"]",
"log",
".",
"debug",
"(",
"\"Collecting python sources for pot ...\"",
")",
"for",
"source_path",
"in",
"self",
".",
"_source_paths",
":",
"for",
"source_path",
"in",
"self",
".",
"_i... | bbccedd11b18d925ad4c062b5eb65981e24d0433 |
train | TranslationGenerator.do_po | Update all po files with the data in the pot reference file. | scripts/distribution/translation_generator.py | def do_po(self):
"""
Update all po files with the data in the pot reference file.
"""
log.debug("Start updating po files ...")
pot_path = (self._po_path / self._basename).with_suffix(".pot")
for po_dir_path in self._iter_po_dir():
po_path = (po_dir_path / self... | def do_po(self):
"""
Update all po files with the data in the pot reference file.
"""
log.debug("Start updating po files ...")
pot_path = (self._po_path / self._basename).with_suffix(".pot")
for po_dir_path in self._iter_po_dir():
po_path = (po_dir_path / self... | [
"Update",
"all",
"po",
"files",
"with",
"the",
"data",
"in",
"the",
"pot",
"reference",
"file",
"."
] | subdownloader/subdownloader | python | https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/scripts/distribution/translation_generator.py#L78-L97 | [
"def",
"do_po",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Start updating po files ...\"",
")",
"pot_path",
"=",
"(",
"self",
".",
"_po_path",
"/",
"self",
".",
"_basename",
")",
".",
"with_suffix",
"(",
"\".pot\"",
")",
"for",
"po_dir_path",
"in"... | bbccedd11b18d925ad4c062b5eb65981e24d0433 |
train | TranslationGenerator.do_mo | Generate mo files for all po files. | scripts/distribution/translation_generator.py | def do_mo(self):
"""
Generate mo files for all po files.
"""
log.debug("Start updating mo files ...")
for po_dir_path in self._iter_po_dir():
po_path = (po_dir_path / self._basename).with_suffix(".po")
lc_path = self._mo_path / po_dir_path.name / "LC_MESSA... | def do_mo(self):
"""
Generate mo files for all po files.
"""
log.debug("Start updating mo files ...")
for po_dir_path in self._iter_po_dir():
po_path = (po_dir_path / self._basename).with_suffix(".po")
lc_path = self._mo_path / po_dir_path.name / "LC_MESSA... | [
"Generate",
"mo",
"files",
"for",
"all",
"po",
"files",
"."
] | subdownloader/subdownloader | python | https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/scripts/distribution/translation_generator.py#L99-L111 | [
"def",
"do_mo",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Start updating mo files ...\"",
")",
"for",
"po_dir_path",
"in",
"self",
".",
"_iter_po_dir",
"(",
")",
":",
"po_path",
"=",
"(",
"po_dir_path",
"/",
"self",
".",
"_basename",
")",
".",
... | bbccedd11b18d925ad4c062b5eb65981e24d0433 |
train | Worker.run | Runs the worker and consumes messages from RabbitMQ.
Returns only after `shutdown()` is called. | kuyruk/worker.py | def run(self) -> None:
"""Runs the worker and consumes messages from RabbitMQ.
Returns only after `shutdown()` is called.
"""
if self._logging_level:
logging.basicConfig(
level=getattr(logging, self._logging_level.upper()),
format="%(levelname... | def run(self) -> None:
"""Runs the worker and consumes messages from RabbitMQ.
Returns only after `shutdown()` is called.
"""
if self._logging_level:
logging.basicConfig(
level=getattr(logging, self._logging_level.upper()),
format="%(levelname... | [
"Runs",
"the",
"worker",
"and",
"consumes",
"messages",
"from",
"RabbitMQ",
".",
"Returns",
"only",
"after",
"shutdown",
"()",
"is",
"called",
"."
] | cenkalti/kuyruk | python | https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L81-L115 | [
"def",
"run",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_logging_level",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"getattr",
"(",
"logging",
",",
"self",
".",
"_logging_level",
".",
"upper",
"(",
")",
")",
",",
"format",
... | c99d66be9d8fb077610f2fa883d5a1d268b42f04 |
train | Worker._process_message | Processes the message received from the queue. | kuyruk/worker.py | def _process_message(self, message: amqp.Message) -> None:
"""Processes the message received from the queue."""
if self.shutdown_pending.is_set():
return
try:
if isinstance(message.body, bytes):
message.body = message.body.decode()
description... | def _process_message(self, message: amqp.Message) -> None:
"""Processes the message received from the queue."""
if self.shutdown_pending.is_set():
return
try:
if isinstance(message.body, bytes):
message.body = message.body.decode()
description... | [
"Processes",
"the",
"message",
"received",
"from",
"the",
"queue",
"."
] | cenkalti/kuyruk | python | https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L175-L190 | [
"def",
"_process_message",
"(",
"self",
",",
"message",
":",
"amqp",
".",
"Message",
")",
"->",
"None",
":",
"if",
"self",
".",
"shutdown_pending",
".",
"is_set",
"(",
")",
":",
"return",
"try",
":",
"if",
"isinstance",
"(",
"message",
".",
"body",
","... | c99d66be9d8fb077610f2fa883d5a1d268b42f04 |
train | Worker._apply_task | Logs the time spent while running the task. | kuyruk/worker.py | def _apply_task(task: Task, args: Tuple, kwargs: Dict[str, Any]) -> Any:
"""Logs the time spent while running the task."""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
start = monotonic()
try:
return task.apply(*args, **kwargs)
... | def _apply_task(task: Task, args: Tuple, kwargs: Dict[str, Any]) -> Any:
"""Logs the time spent while running the task."""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
start = monotonic()
try:
return task.apply(*args, **kwargs)
... | [
"Logs",
"the",
"time",
"spent",
"while",
"running",
"the",
"task",
"."
] | cenkalti/kuyruk | python | https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L292-L304 | [
"def",
"_apply_task",
"(",
"task",
":",
"Task",
",",
"args",
":",
"Tuple",
",",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Any",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"(",
")",
"if",
"kwargs",
"is",
"None",
":"... | c99d66be9d8fb077610f2fa883d5a1d268b42f04 |
train | Worker._shutdown_timer | Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown
gracefully. | kuyruk/worker.py | def _shutdown_timer(self) -> None:
"""Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown
gracefully.
"""
remaining = self._max_run_time - self.uptime
if not self.shutdown_pending.wait(remaining):
logger.warning('Run time reached zero')
sel... | def _shutdown_timer(self) -> None:
"""Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown
gracefully.
"""
remaining = self._max_run_time - self.uptime
if not self.shutdown_pending.wait(remaining):
logger.warning('Run time reached zero')
sel... | [
"Counts",
"down",
"from",
"MAX_WORKER_RUN_TIME",
".",
"When",
"it",
"reaches",
"zero",
"sutdown",
"gracefully",
"."
] | cenkalti/kuyruk | python | https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L351-L359 | [
"def",
"_shutdown_timer",
"(",
"self",
")",
"->",
"None",
":",
"remaining",
"=",
"self",
".",
"_max_run_time",
"-",
"self",
".",
"uptime",
"if",
"not",
"self",
".",
"shutdown_pending",
".",
"wait",
"(",
"remaining",
")",
":",
"logger",
".",
"warning",
"(... | c99d66be9d8fb077610f2fa883d5a1d268b42f04 |
train | Worker._handle_sigint | Shutdown after processing current task. | kuyruk/worker.py | def _handle_sigint(self, signum: int, frame: Any) -> None:
"""Shutdown after processing current task."""
logger.warning("Catched SIGINT")
self.shutdown() | def _handle_sigint(self, signum: int, frame: Any) -> None:
"""Shutdown after processing current task."""
logger.warning("Catched SIGINT")
self.shutdown() | [
"Shutdown",
"after",
"processing",
"current",
"task",
"."
] | cenkalti/kuyruk | python | https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L366-L369 | [
"def",
"_handle_sigint",
"(",
"self",
",",
"signum",
":",
"int",
",",
"frame",
":",
"Any",
")",
"->",
"None",
":",
"logger",
".",
"warning",
"(",
"\"Catched SIGINT\"",
")",
"self",
".",
"shutdown",
"(",
")"
] | c99d66be9d8fb077610f2fa883d5a1d268b42f04 |
train | Worker._handle_sighup | Used internally to fail the task when connection to RabbitMQ is
lost during the execution of the task. | kuyruk/worker.py | def _handle_sighup(self, signum: int, frame: Any) -> None:
"""Used internally to fail the task when connection to RabbitMQ is
lost during the execution of the task.
"""
logger.warning("Catched SIGHUP")
exc_info = self._heartbeat_exc_info
self._heartbeat_exc_info = None
... | def _handle_sighup(self, signum: int, frame: Any) -> None:
"""Used internally to fail the task when connection to RabbitMQ is
lost during the execution of the task.
"""
logger.warning("Catched SIGHUP")
exc_info = self._heartbeat_exc_info
self._heartbeat_exc_info = None
... | [
"Used",
"internally",
"to",
"fail",
"the",
"task",
"when",
"connection",
"to",
"RabbitMQ",
"is",
"lost",
"during",
"the",
"execution",
"of",
"the",
"task",
"."
] | cenkalti/kuyruk | python | https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L376-L386 | [
"def",
"_handle_sighup",
"(",
"self",
",",
"signum",
":",
"int",
",",
"frame",
":",
"Any",
")",
"->",
"None",
":",
"logger",
".",
"warning",
"(",
"\"Catched SIGHUP\"",
")",
"exc_info",
"=",
"self",
".",
"_heartbeat_exc_info",
"self",
".",
"_heartbeat_exc_inf... | c99d66be9d8fb077610f2fa883d5a1d268b42f04 |
train | Worker._handle_sigusr1 | Print stacktrace. | kuyruk/worker.py | def _handle_sigusr1(signum: int, frame: Any) -> None:
"""Print stacktrace."""
print('=' * 70)
print(''.join(traceback.format_stack()))
print('-' * 70) | def _handle_sigusr1(signum: int, frame: Any) -> None:
"""Print stacktrace."""
print('=' * 70)
print(''.join(traceback.format_stack()))
print('-' * 70) | [
"Print",
"stacktrace",
"."
] | cenkalti/kuyruk | python | https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L389-L393 | [
"def",
"_handle_sigusr1",
"(",
"signum",
":",
"int",
",",
"frame",
":",
"Any",
")",
"->",
"None",
":",
"print",
"(",
"'='",
"*",
"70",
")",
"print",
"(",
"''",
".",
"join",
"(",
"traceback",
".",
"format_stack",
"(",
")",
")",
")",
"print",
"(",
... | c99d66be9d8fb077610f2fa883d5a1d268b42f04 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.