repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
googlefonts/ufo2ft | Lib/ufo2ft/featureWriters/baseFeatureWriter.py | BaseFeatureWriter.compileGSUB | def compileGSUB(self):
"""Compile a temporary GSUB table from the current feature file.
"""
from ufo2ft.util import compileGSUB
compiler = self.context.compiler
if compiler is not None:
# The result is cached in the compiler instance, so if another
# writer requests one it is not compiled again.
if hasattr(compiler, "_gsub"):
return compiler._gsub
glyphOrder = compiler.ttFont.getGlyphOrder()
else:
# the 'real' glyph order doesn't matter because the table is not
# compiled to binary, only the glyph names are used
glyphOrder = sorted(self.context.font.keys())
gsub = compileGSUB(self.context.feaFile, glyphOrder)
if compiler and not hasattr(compiler, "_gsub"):
compiler._gsub = gsub
return gsub | python | def compileGSUB(self):
"""Compile a temporary GSUB table from the current feature file.
"""
from ufo2ft.util import compileGSUB
compiler = self.context.compiler
if compiler is not None:
# The result is cached in the compiler instance, so if another
# writer requests one it is not compiled again.
if hasattr(compiler, "_gsub"):
return compiler._gsub
glyphOrder = compiler.ttFont.getGlyphOrder()
else:
# the 'real' glyph order doesn't matter because the table is not
# compiled to binary, only the glyph names are used
glyphOrder = sorted(self.context.font.keys())
gsub = compileGSUB(self.context.feaFile, glyphOrder)
if compiler and not hasattr(compiler, "_gsub"):
compiler._gsub = gsub
return gsub | [
"def",
"compileGSUB",
"(",
"self",
")",
":",
"from",
"ufo2ft",
".",
"util",
"import",
"compileGSUB",
"compiler",
"=",
"self",
".",
"context",
".",
"compiler",
"if",
"compiler",
"is",
"not",
"None",
":",
"# The result is cached in the compiler instance, so if another... | Compile a temporary GSUB table from the current feature file. | [
"Compile",
"a",
"temporary",
"GSUB",
"table",
"from",
"the",
"current",
"feature",
"file",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureWriters/baseFeatureWriter.py#L163-L185 | train | 24,100 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.compile | def compile(self):
"""
Compile the OpenType binary.
"""
self.otf = TTFont(sfntVersion=self.sfntVersion)
# only compile vertical metrics tables if vhea metrics a defined
vertical_metrics = [
"openTypeVheaVertTypoAscender",
"openTypeVheaVertTypoDescender",
"openTypeVheaVertTypoLineGap",
"openTypeVheaCaretSlopeRise",
"openTypeVheaCaretSlopeRun",
"openTypeVheaCaretOffset",
]
self.vertical = all(
getAttrWithFallback(self.ufo.info, metric) is not None
for metric in vertical_metrics
)
# write the glyph order
self.otf.setGlyphOrder(self.glyphOrder)
# populate basic tables
self.setupTable_head()
self.setupTable_hmtx()
self.setupTable_hhea()
self.setupTable_name()
self.setupTable_maxp()
self.setupTable_cmap()
self.setupTable_OS2()
self.setupTable_post()
if self.vertical:
self.setupTable_vmtx()
self.setupTable_vhea()
self.setupOtherTables()
self.importTTX()
return self.otf | python | def compile(self):
"""
Compile the OpenType binary.
"""
self.otf = TTFont(sfntVersion=self.sfntVersion)
# only compile vertical metrics tables if vhea metrics a defined
vertical_metrics = [
"openTypeVheaVertTypoAscender",
"openTypeVheaVertTypoDescender",
"openTypeVheaVertTypoLineGap",
"openTypeVheaCaretSlopeRise",
"openTypeVheaCaretSlopeRun",
"openTypeVheaCaretOffset",
]
self.vertical = all(
getAttrWithFallback(self.ufo.info, metric) is not None
for metric in vertical_metrics
)
# write the glyph order
self.otf.setGlyphOrder(self.glyphOrder)
# populate basic tables
self.setupTable_head()
self.setupTable_hmtx()
self.setupTable_hhea()
self.setupTable_name()
self.setupTable_maxp()
self.setupTable_cmap()
self.setupTable_OS2()
self.setupTable_post()
if self.vertical:
self.setupTable_vmtx()
self.setupTable_vhea()
self.setupOtherTables()
self.importTTX()
return self.otf | [
"def",
"compile",
"(",
"self",
")",
":",
"self",
".",
"otf",
"=",
"TTFont",
"(",
"sfntVersion",
"=",
"self",
".",
"sfntVersion",
")",
"# only compile vertical metrics tables if vhea metrics a defined",
"vertical_metrics",
"=",
"[",
"\"openTypeVheaVertTypoAscender\"",
",... | Compile the OpenType binary. | [
"Compile",
"the",
"OpenType",
"binary",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L94-L132 | train | 24,101 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.makeFontBoundingBox | def makeFontBoundingBox(self):
"""
Make a bounding box for the font.
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired.
"""
if not hasattr(self, "glyphBoundingBoxes"):
self.glyphBoundingBoxes = self.makeGlyphsBoundingBoxes()
fontBox = None
for glyphName, glyphBox in self.glyphBoundingBoxes.items():
if glyphBox is None:
continue
if fontBox is None:
fontBox = glyphBox
else:
fontBox = unionRect(fontBox, glyphBox)
if fontBox is None: # unlikely
fontBox = BoundingBox(0, 0, 0, 0)
return fontBox | python | def makeFontBoundingBox(self):
"""
Make a bounding box for the font.
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired.
"""
if not hasattr(self, "glyphBoundingBoxes"):
self.glyphBoundingBoxes = self.makeGlyphsBoundingBoxes()
fontBox = None
for glyphName, glyphBox in self.glyphBoundingBoxes.items():
if glyphBox is None:
continue
if fontBox is None:
fontBox = glyphBox
else:
fontBox = unionRect(fontBox, glyphBox)
if fontBox is None: # unlikely
fontBox = BoundingBox(0, 0, 0, 0)
return fontBox | [
"def",
"makeFontBoundingBox",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"glyphBoundingBoxes\"",
")",
":",
"self",
".",
"glyphBoundingBoxes",
"=",
"self",
".",
"makeGlyphsBoundingBoxes",
"(",
")",
"fontBox",
"=",
"None",
"for",
"glyphNa... | Make a bounding box for the font.
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired. | [
"Make",
"a",
"bounding",
"box",
"for",
"the",
"font",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L164-L184 | train | 24,102 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.makeMissingRequiredGlyphs | def makeMissingRequiredGlyphs(font, glyphSet):
"""
Add .notdef to the glyph set if it is not present.
**This should not be called externally.** Subclasses
may override this method to handle the glyph creation
in a different way if desired.
"""
if ".notdef" in glyphSet:
return
unitsPerEm = otRound(getAttrWithFallback(font.info, "unitsPerEm"))
ascender = otRound(getAttrWithFallback(font.info, "ascender"))
descender = otRound(getAttrWithFallback(font.info, "descender"))
defaultWidth = otRound(unitsPerEm * 0.5)
glyphSet[".notdef"] = StubGlyph(name=".notdef",
width=defaultWidth,
unitsPerEm=unitsPerEm,
ascender=ascender,
descender=descender) | python | def makeMissingRequiredGlyphs(font, glyphSet):
"""
Add .notdef to the glyph set if it is not present.
**This should not be called externally.** Subclasses
may override this method to handle the glyph creation
in a different way if desired.
"""
if ".notdef" in glyphSet:
return
unitsPerEm = otRound(getAttrWithFallback(font.info, "unitsPerEm"))
ascender = otRound(getAttrWithFallback(font.info, "ascender"))
descender = otRound(getAttrWithFallback(font.info, "descender"))
defaultWidth = otRound(unitsPerEm * 0.5)
glyphSet[".notdef"] = StubGlyph(name=".notdef",
width=defaultWidth,
unitsPerEm=unitsPerEm,
ascender=ascender,
descender=descender) | [
"def",
"makeMissingRequiredGlyphs",
"(",
"font",
",",
"glyphSet",
")",
":",
"if",
"\".notdef\"",
"in",
"glyphSet",
":",
"return",
"unitsPerEm",
"=",
"otRound",
"(",
"getAttrWithFallback",
"(",
"font",
".",
"info",
",",
"\"unitsPerEm\"",
")",
")",
"ascender",
"... | Add .notdef to the glyph set if it is not present.
**This should not be called externally.** Subclasses
may override this method to handle the glyph creation
in a different way if desired. | [
"Add",
".",
"notdef",
"to",
"the",
"glyph",
"set",
"if",
"it",
"is",
"not",
"present",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L197-L216 | train | 24,103 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.setupTable_head | def setupTable_head(self):
"""
Make the head table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "head" not in self.tables:
return
self.otf["head"] = head = newTable("head")
font = self.ufo
head.checkSumAdjustment = 0
head.tableVersion = 1.0
head.magicNumber = 0x5F0F3CF5
# version numbers
# limit minor version to 3 digits as recommended in OpenType spec:
# https://www.microsoft.com/typography/otspec/recom.htm
versionMajor = getAttrWithFallback(font.info, "versionMajor")
versionMinor = getAttrWithFallback(font.info, "versionMinor")
fullFontRevision = float("%d.%03d" % (versionMajor, versionMinor))
head.fontRevision = round(fullFontRevision, 3)
if head.fontRevision != fullFontRevision:
logger.warning(
"Minor version in %s has too many digits and won't fit into "
"the head table's fontRevision field; rounded to %s.",
fullFontRevision, head.fontRevision)
# upm
head.unitsPerEm = otRound(getAttrWithFallback(font.info, "unitsPerEm"))
# times
head.created = dateStringToTimeValue(getAttrWithFallback(font.info, "openTypeHeadCreated")) - mac_epoch_diff
head.modified = dateStringToTimeValue(dateStringForNow()) - mac_epoch_diff
# bounding box
xMin, yMin, xMax, yMax = self.fontBoundingBox
head.xMin = otRound(xMin)
head.yMin = otRound(yMin)
head.xMax = otRound(xMax)
head.yMax = otRound(yMax)
# style mapping
styleMapStyleName = getAttrWithFallback(font.info, "styleMapStyleName")
macStyle = []
if styleMapStyleName == "bold":
macStyle = [0]
elif styleMapStyleName == "bold italic":
macStyle = [0, 1]
elif styleMapStyleName == "italic":
macStyle = [1]
head.macStyle = intListToNum(macStyle, 0, 16)
# misc
head.flags = intListToNum(getAttrWithFallback(font.info, "openTypeHeadFlags"), 0, 16)
head.lowestRecPPEM = otRound(getAttrWithFallback(font.info, "openTypeHeadLowestRecPPEM"))
head.fontDirectionHint = 2
head.indexToLocFormat = 0
head.glyphDataFormat = 0 | python | def setupTable_head(self):
"""
Make the head table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "head" not in self.tables:
return
self.otf["head"] = head = newTable("head")
font = self.ufo
head.checkSumAdjustment = 0
head.tableVersion = 1.0
head.magicNumber = 0x5F0F3CF5
# version numbers
# limit minor version to 3 digits as recommended in OpenType spec:
# https://www.microsoft.com/typography/otspec/recom.htm
versionMajor = getAttrWithFallback(font.info, "versionMajor")
versionMinor = getAttrWithFallback(font.info, "versionMinor")
fullFontRevision = float("%d.%03d" % (versionMajor, versionMinor))
head.fontRevision = round(fullFontRevision, 3)
if head.fontRevision != fullFontRevision:
logger.warning(
"Minor version in %s has too many digits and won't fit into "
"the head table's fontRevision field; rounded to %s.",
fullFontRevision, head.fontRevision)
# upm
head.unitsPerEm = otRound(getAttrWithFallback(font.info, "unitsPerEm"))
# times
head.created = dateStringToTimeValue(getAttrWithFallback(font.info, "openTypeHeadCreated")) - mac_epoch_diff
head.modified = dateStringToTimeValue(dateStringForNow()) - mac_epoch_diff
# bounding box
xMin, yMin, xMax, yMax = self.fontBoundingBox
head.xMin = otRound(xMin)
head.yMin = otRound(yMin)
head.xMax = otRound(xMax)
head.yMax = otRound(yMax)
# style mapping
styleMapStyleName = getAttrWithFallback(font.info, "styleMapStyleName")
macStyle = []
if styleMapStyleName == "bold":
macStyle = [0]
elif styleMapStyleName == "bold italic":
macStyle = [0, 1]
elif styleMapStyleName == "italic":
macStyle = [1]
head.macStyle = intListToNum(macStyle, 0, 16)
# misc
head.flags = intListToNum(getAttrWithFallback(font.info, "openTypeHeadFlags"), 0, 16)
head.lowestRecPPEM = otRound(getAttrWithFallback(font.info, "openTypeHeadLowestRecPPEM"))
head.fontDirectionHint = 2
head.indexToLocFormat = 0
head.glyphDataFormat = 0 | [
"def",
"setupTable_head",
"(",
"self",
")",
":",
"if",
"\"head\"",
"not",
"in",
"self",
".",
"tables",
":",
"return",
"self",
".",
"otf",
"[",
"\"head\"",
"]",
"=",
"head",
"=",
"newTable",
"(",
"\"head\"",
")",
"font",
"=",
"self",
".",
"ufo",
"head... | Make the head table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired. | [
"Make",
"the",
"head",
"table",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L245-L305 | train | 24,104 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.setupTable_name | def setupTable_name(self):
"""
Make the name table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "name" not in self.tables:
return
font = self.ufo
self.otf["name"] = name = newTable("name")
name.names = []
# Set name records from font.info.openTypeNameRecords
for nameRecord in getAttrWithFallback(
font.info, "openTypeNameRecords"):
nameId = nameRecord["nameID"]
platformId = nameRecord["platformID"]
platEncId = nameRecord["encodingID"]
langId = nameRecord["languageID"]
# on Python 2, plistLib (used by ufoLib) returns unicode strings
# only when plist data contain non-ascii characters, and returns
# ascii-encoded bytes when it can. On the other hand, fontTools's
# name table `setName` method wants unicode strings, so we must
# decode them first
nameVal = tounicode(nameRecord["string"], encoding='ascii')
name.setName(nameVal, nameId, platformId, platEncId, langId)
# Build name records
familyName = getAttrWithFallback(font.info, "styleMapFamilyName")
styleName = getAttrWithFallback(font.info, "styleMapStyleName").title()
preferredFamilyName = getAttrWithFallback(
font.info, "openTypeNamePreferredFamilyName")
preferredSubfamilyName = getAttrWithFallback(
font.info, "openTypeNamePreferredSubfamilyName")
fullName = "%s %s" % (preferredFamilyName, preferredSubfamilyName)
nameVals = {
0: getAttrWithFallback(font.info, "copyright"),
1: familyName,
2: styleName,
3: getAttrWithFallback(font.info, "openTypeNameUniqueID"),
4: fullName,
5: getAttrWithFallback(font.info, "openTypeNameVersion"),
6: getAttrWithFallback(font.info, "postscriptFontName"),
7: getAttrWithFallback(font.info, "trademark"),
8: getAttrWithFallback(font.info, "openTypeNameManufacturer"),
9: getAttrWithFallback(font.info, "openTypeNameDesigner"),
10: getAttrWithFallback(font.info, "openTypeNameDescription"),
11: getAttrWithFallback(font.info, "openTypeNameManufacturerURL"),
12: getAttrWithFallback(font.info, "openTypeNameDesignerURL"),
13: getAttrWithFallback(font.info, "openTypeNameLicense"),
14: getAttrWithFallback(font.info, "openTypeNameLicenseURL"),
16: preferredFamilyName,
17: preferredSubfamilyName,
}
# don't add typographic names if they are the same as the legacy ones
if nameVals[1] == nameVals[16]:
del nameVals[16]
if nameVals[2] == nameVals[17]:
del nameVals[17]
# postscript font name
if nameVals[6]:
nameVals[6] = normalizeStringForPostscript(nameVals[6])
for nameId in sorted(nameVals.keys()):
nameVal = nameVals[nameId]
if not nameVal:
continue
nameVal = tounicode(nameVal, encoding='ascii')
platformId = 3
platEncId = 10 if _isNonBMP(nameVal) else 1
langId = 0x409
# Set built name record if not set yet
if name.getName(nameId, platformId, platEncId, langId):
continue
name.setName(nameVal, nameId, platformId, platEncId, langId) | python | def setupTable_name(self):
"""
Make the name table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "name" not in self.tables:
return
font = self.ufo
self.otf["name"] = name = newTable("name")
name.names = []
# Set name records from font.info.openTypeNameRecords
for nameRecord in getAttrWithFallback(
font.info, "openTypeNameRecords"):
nameId = nameRecord["nameID"]
platformId = nameRecord["platformID"]
platEncId = nameRecord["encodingID"]
langId = nameRecord["languageID"]
# on Python 2, plistLib (used by ufoLib) returns unicode strings
# only when plist data contain non-ascii characters, and returns
# ascii-encoded bytes when it can. On the other hand, fontTools's
# name table `setName` method wants unicode strings, so we must
# decode them first
nameVal = tounicode(nameRecord["string"], encoding='ascii')
name.setName(nameVal, nameId, platformId, platEncId, langId)
# Build name records
familyName = getAttrWithFallback(font.info, "styleMapFamilyName")
styleName = getAttrWithFallback(font.info, "styleMapStyleName").title()
preferredFamilyName = getAttrWithFallback(
font.info, "openTypeNamePreferredFamilyName")
preferredSubfamilyName = getAttrWithFallback(
font.info, "openTypeNamePreferredSubfamilyName")
fullName = "%s %s" % (preferredFamilyName, preferredSubfamilyName)
nameVals = {
0: getAttrWithFallback(font.info, "copyright"),
1: familyName,
2: styleName,
3: getAttrWithFallback(font.info, "openTypeNameUniqueID"),
4: fullName,
5: getAttrWithFallback(font.info, "openTypeNameVersion"),
6: getAttrWithFallback(font.info, "postscriptFontName"),
7: getAttrWithFallback(font.info, "trademark"),
8: getAttrWithFallback(font.info, "openTypeNameManufacturer"),
9: getAttrWithFallback(font.info, "openTypeNameDesigner"),
10: getAttrWithFallback(font.info, "openTypeNameDescription"),
11: getAttrWithFallback(font.info, "openTypeNameManufacturerURL"),
12: getAttrWithFallback(font.info, "openTypeNameDesignerURL"),
13: getAttrWithFallback(font.info, "openTypeNameLicense"),
14: getAttrWithFallback(font.info, "openTypeNameLicenseURL"),
16: preferredFamilyName,
17: preferredSubfamilyName,
}
# don't add typographic names if they are the same as the legacy ones
if nameVals[1] == nameVals[16]:
del nameVals[16]
if nameVals[2] == nameVals[17]:
del nameVals[17]
# postscript font name
if nameVals[6]:
nameVals[6] = normalizeStringForPostscript(nameVals[6])
for nameId in sorted(nameVals.keys()):
nameVal = nameVals[nameId]
if not nameVal:
continue
nameVal = tounicode(nameVal, encoding='ascii')
platformId = 3
platEncId = 10 if _isNonBMP(nameVal) else 1
langId = 0x409
# Set built name record if not set yet
if name.getName(nameId, platformId, platEncId, langId):
continue
name.setName(nameVal, nameId, platformId, platEncId, langId) | [
"def",
"setupTable_name",
"(",
"self",
")",
":",
"if",
"\"name\"",
"not",
"in",
"self",
".",
"tables",
":",
"return",
"font",
"=",
"self",
".",
"ufo",
"self",
".",
"otf",
"[",
"\"name\"",
"]",
"=",
"name",
"=",
"newTable",
"(",
"\"name\"",
")",
"name... | Make the name table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired. | [
"Make",
"the",
"name",
"table",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L307-L386 | train | 24,105 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.setupTable_cmap | def setupTable_cmap(self):
"""
Make the cmap table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "cmap" not in self.tables:
return
from fontTools.ttLib.tables._c_m_a_p import cmap_format_4
nonBMP = dict((k,v) for k,v in self.unicodeToGlyphNameMapping.items() if k > 65535)
if nonBMP:
mapping = dict((k,v) for k,v in self.unicodeToGlyphNameMapping.items() if k <= 65535)
else:
mapping = dict(self.unicodeToGlyphNameMapping)
# mac
cmap4_0_3 = cmap_format_4(4)
cmap4_0_3.platformID = 0
cmap4_0_3.platEncID = 3
cmap4_0_3.language = 0
cmap4_0_3.cmap = mapping
# windows
cmap4_3_1 = cmap_format_4(4)
cmap4_3_1.platformID = 3
cmap4_3_1.platEncID = 1
cmap4_3_1.language = 0
cmap4_3_1.cmap = mapping
# store
self.otf["cmap"] = cmap = newTable("cmap")
cmap.tableVersion = 0
cmap.tables = [cmap4_0_3, cmap4_3_1]
# If we have glyphs outside Unicode BMP, we must set another
# subtable that can hold longer codepoints for them.
if nonBMP:
from fontTools.ttLib.tables._c_m_a_p import cmap_format_12
nonBMP.update(mapping)
# mac
cmap12_0_4 = cmap_format_12(12)
cmap12_0_4.platformID = 0
cmap12_0_4.platEncID = 4
cmap12_0_4.language = 0
cmap12_0_4.cmap = nonBMP
# windows
cmap12_3_10 = cmap_format_12(12)
cmap12_3_10.platformID = 3
cmap12_3_10.platEncID = 10
cmap12_3_10.language = 0
cmap12_3_10.cmap = nonBMP
# update tables registry
cmap.tables = [cmap4_0_3, cmap4_3_1, cmap12_0_4, cmap12_3_10] | python | def setupTable_cmap(self):
"""
Make the cmap table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "cmap" not in self.tables:
return
from fontTools.ttLib.tables._c_m_a_p import cmap_format_4
nonBMP = dict((k,v) for k,v in self.unicodeToGlyphNameMapping.items() if k > 65535)
if nonBMP:
mapping = dict((k,v) for k,v in self.unicodeToGlyphNameMapping.items() if k <= 65535)
else:
mapping = dict(self.unicodeToGlyphNameMapping)
# mac
cmap4_0_3 = cmap_format_4(4)
cmap4_0_3.platformID = 0
cmap4_0_3.platEncID = 3
cmap4_0_3.language = 0
cmap4_0_3.cmap = mapping
# windows
cmap4_3_1 = cmap_format_4(4)
cmap4_3_1.platformID = 3
cmap4_3_1.platEncID = 1
cmap4_3_1.language = 0
cmap4_3_1.cmap = mapping
# store
self.otf["cmap"] = cmap = newTable("cmap")
cmap.tableVersion = 0
cmap.tables = [cmap4_0_3, cmap4_3_1]
# If we have glyphs outside Unicode BMP, we must set another
# subtable that can hold longer codepoints for them.
if nonBMP:
from fontTools.ttLib.tables._c_m_a_p import cmap_format_12
nonBMP.update(mapping)
# mac
cmap12_0_4 = cmap_format_12(12)
cmap12_0_4.platformID = 0
cmap12_0_4.platEncID = 4
cmap12_0_4.language = 0
cmap12_0_4.cmap = nonBMP
# windows
cmap12_3_10 = cmap_format_12(12)
cmap12_3_10.platformID = 3
cmap12_3_10.platEncID = 10
cmap12_3_10.language = 0
cmap12_3_10.cmap = nonBMP
# update tables registry
cmap.tables = [cmap4_0_3, cmap4_3_1, cmap12_0_4, cmap12_3_10] | [
"def",
"setupTable_cmap",
"(",
"self",
")",
":",
"if",
"\"cmap\"",
"not",
"in",
"self",
".",
"tables",
":",
"return",
"from",
"fontTools",
".",
"ttLib",
".",
"tables",
".",
"_c_m_a_p",
"import",
"cmap_format_4",
"nonBMP",
"=",
"dict",
"(",
"(",
"k",
",",... | Make the cmap table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired. | [
"Make",
"the",
"cmap",
"table",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L398-L450 | train | 24,106 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.setupTable_hmtx | def setupTable_hmtx(self):
"""
Make the hmtx table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "hmtx" not in self.tables:
return
self.otf["hmtx"] = hmtx = newTable("hmtx")
hmtx.metrics = {}
for glyphName, glyph in self.allGlyphs.items():
width = otRound(glyph.width)
if width < 0:
raise ValueError(
"The width should not be negative: '%s'" % (glyphName))
bounds = self.glyphBoundingBoxes[glyphName]
left = bounds.xMin if bounds else 0
hmtx[glyphName] = (width, left) | python | def setupTable_hmtx(self):
"""
Make the hmtx table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "hmtx" not in self.tables:
return
self.otf["hmtx"] = hmtx = newTable("hmtx")
hmtx.metrics = {}
for glyphName, glyph in self.allGlyphs.items():
width = otRound(glyph.width)
if width < 0:
raise ValueError(
"The width should not be negative: '%s'" % (glyphName))
bounds = self.glyphBoundingBoxes[glyphName]
left = bounds.xMin if bounds else 0
hmtx[glyphName] = (width, left) | [
"def",
"setupTable_hmtx",
"(",
"self",
")",
":",
"if",
"\"hmtx\"",
"not",
"in",
"self",
".",
"tables",
":",
"return",
"self",
".",
"otf",
"[",
"\"hmtx\"",
"]",
"=",
"hmtx",
"=",
"newTable",
"(",
"\"hmtx\"",
")",
"hmtx",
".",
"metrics",
"=",
"{",
"}",... | Make the hmtx table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired. | [
"Make",
"the",
"hmtx",
"table",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L613-L633 | train | 24,107 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler._setupTable_hhea_or_vhea | def _setupTable_hhea_or_vhea(self, tag):
"""
Make the hhea table or the vhea table. This assume the hmtx or
the vmtx were respectively made first.
"""
if tag not in self.tables:
return
if tag == "hhea":
isHhea = True
else:
isHhea = False
self.otf[tag] = table = newTable(tag)
mtxTable = self.otf.get(tag[0] + "mtx")
font = self.ufo
if isHhea:
table.tableVersion = 0x00010000
else:
table.tableVersion = 0x00011000
# Vertical metrics in hhea, horizontal metrics in vhea
# and caret info.
# The hhea metrics names are formed as:
# "openType" + tag.title() + "Ascender", etc.
# While vhea metrics names are formed as:
# "openType" + tag.title() + "VertTypo" + "Ascender", etc.
# Caret info names only differ by tag.title().
commonPrefix = "openType%s" % tag.title()
if isHhea:
metricsPrefix = commonPrefix
else:
metricsPrefix = "openType%sVertTypo" % tag.title()
metricsDict = {
"ascent": "%sAscender" % metricsPrefix,
"descent": "%sDescender" % metricsPrefix,
"lineGap": "%sLineGap" % metricsPrefix,
"caretSlopeRise": "%sCaretSlopeRise" % commonPrefix,
"caretSlopeRun": "%sCaretSlopeRun" % commonPrefix,
"caretOffset": "%sCaretOffset" % commonPrefix,
}
for otfName, ufoName in metricsDict.items():
setattr(table, otfName,
otRound(getAttrWithFallback(font.info, ufoName)))
# Horizontal metrics in hhea, vertical metrics in vhea
advances = [] # width in hhea, height in vhea
firstSideBearings = [] # left in hhea, top in vhea
secondSideBearings = [] # right in hhea, bottom in vhea
extents = []
if mtxTable is not None:
for glyphName in self.allGlyphs:
advance, firstSideBearing = mtxTable[glyphName]
advances.append(advance)
bounds = self.glyphBoundingBoxes[glyphName]
if bounds is None:
continue
if isHhea:
boundsAdvance = (bounds.xMax - bounds.xMin)
# equation from the hhea spec for calculating xMaxExtent:
# Max(lsb + (xMax - xMin))
extent = firstSideBearing + boundsAdvance
else:
boundsAdvance = (bounds.yMax - bounds.yMin)
# equation from the vhea spec for calculating yMaxExtent:
# Max(tsb + (yMax - yMin)).
extent = firstSideBearing + boundsAdvance
secondSideBearing = advance - firstSideBearing - boundsAdvance
firstSideBearings.append(firstSideBearing)
secondSideBearings.append(secondSideBearing)
extents.append(extent)
setattr(table,
"advance%sMax" % ("Width" if isHhea else "Height"),
max(advances) if advances else 0)
setattr(table,
"min%sSideBearing" % ("Left" if isHhea else "Top"),
min(firstSideBearings) if firstSideBearings else 0)
setattr(table,
"min%sSideBearing" % ("Right" if isHhea else "Bottom"),
min(secondSideBearings) if secondSideBearings else 0)
setattr(table,
"%sMaxExtent" % ("x" if isHhea else "y"),
max(extents) if extents else 0)
if isHhea:
reserved = range(4)
else:
# vhea.reserved0 is caretOffset for legacy reasons
reserved = range(1, 5)
for i in reserved:
setattr(table, "reserved%i" % i, 0)
table.metricDataFormat = 0
# glyph count
setattr(table,
"numberOf%sMetrics" % ("H" if isHhea else "V"),
len(self.allGlyphs)) | python | def _setupTable_hhea_or_vhea(self, tag):
"""
Make the hhea table or the vhea table. This assume the hmtx or
the vmtx were respectively made first.
"""
if tag not in self.tables:
return
if tag == "hhea":
isHhea = True
else:
isHhea = False
self.otf[tag] = table = newTable(tag)
mtxTable = self.otf.get(tag[0] + "mtx")
font = self.ufo
if isHhea:
table.tableVersion = 0x00010000
else:
table.tableVersion = 0x00011000
# Vertical metrics in hhea, horizontal metrics in vhea
# and caret info.
# The hhea metrics names are formed as:
# "openType" + tag.title() + "Ascender", etc.
# While vhea metrics names are formed as:
# "openType" + tag.title() + "VertTypo" + "Ascender", etc.
# Caret info names only differ by tag.title().
commonPrefix = "openType%s" % tag.title()
if isHhea:
metricsPrefix = commonPrefix
else:
metricsPrefix = "openType%sVertTypo" % tag.title()
metricsDict = {
"ascent": "%sAscender" % metricsPrefix,
"descent": "%sDescender" % metricsPrefix,
"lineGap": "%sLineGap" % metricsPrefix,
"caretSlopeRise": "%sCaretSlopeRise" % commonPrefix,
"caretSlopeRun": "%sCaretSlopeRun" % commonPrefix,
"caretOffset": "%sCaretOffset" % commonPrefix,
}
for otfName, ufoName in metricsDict.items():
setattr(table, otfName,
otRound(getAttrWithFallback(font.info, ufoName)))
# Horizontal metrics in hhea, vertical metrics in vhea
advances = [] # width in hhea, height in vhea
firstSideBearings = [] # left in hhea, top in vhea
secondSideBearings = [] # right in hhea, bottom in vhea
extents = []
if mtxTable is not None:
for glyphName in self.allGlyphs:
advance, firstSideBearing = mtxTable[glyphName]
advances.append(advance)
bounds = self.glyphBoundingBoxes[glyphName]
if bounds is None:
continue
if isHhea:
boundsAdvance = (bounds.xMax - bounds.xMin)
# equation from the hhea spec for calculating xMaxExtent:
# Max(lsb + (xMax - xMin))
extent = firstSideBearing + boundsAdvance
else:
boundsAdvance = (bounds.yMax - bounds.yMin)
# equation from the vhea spec for calculating yMaxExtent:
# Max(tsb + (yMax - yMin)).
extent = firstSideBearing + boundsAdvance
secondSideBearing = advance - firstSideBearing - boundsAdvance
firstSideBearings.append(firstSideBearing)
secondSideBearings.append(secondSideBearing)
extents.append(extent)
setattr(table,
"advance%sMax" % ("Width" if isHhea else "Height"),
max(advances) if advances else 0)
setattr(table,
"min%sSideBearing" % ("Left" if isHhea else "Top"),
min(firstSideBearings) if firstSideBearings else 0)
setattr(table,
"min%sSideBearing" % ("Right" if isHhea else "Bottom"),
min(secondSideBearings) if secondSideBearings else 0)
setattr(table,
"%sMaxExtent" % ("x" if isHhea else "y"),
max(extents) if extents else 0)
if isHhea:
reserved = range(4)
else:
# vhea.reserved0 is caretOffset for legacy reasons
reserved = range(1, 5)
for i in reserved:
setattr(table, "reserved%i" % i, 0)
table.metricDataFormat = 0
# glyph count
setattr(table,
"numberOf%sMetrics" % ("H" if isHhea else "V"),
len(self.allGlyphs)) | [
"def",
"_setupTable_hhea_or_vhea",
"(",
"self",
",",
"tag",
")",
":",
"if",
"tag",
"not",
"in",
"self",
".",
"tables",
":",
"return",
"if",
"tag",
"==",
"\"hhea\"",
":",
"isHhea",
"=",
"True",
"else",
":",
"isHhea",
"=",
"False",
"self",
".",
"otf",
... | Make the hhea table or the vhea table. This assume the hmtx or
the vmtx were respectively made first. | [
"Make",
"the",
"hhea",
"table",
"or",
"the",
"vhea",
"table",
".",
"This",
"assume",
"the",
"hmtx",
"or",
"the",
"vmtx",
"were",
"respectively",
"made",
"first",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L635-L727 | train | 24,108 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.setupTable_vmtx | def setupTable_vmtx(self):
"""
Make the vmtx table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "vmtx" not in self.tables:
return
self.otf["vmtx"] = vmtx = newTable("vmtx")
vmtx.metrics = {}
for glyphName, glyph in self.allGlyphs.items():
height = otRound(glyph.height)
if height < 0:
raise ValueError(
"The height should not be negative: '%s'" % (glyphName))
verticalOrigin = _getVerticalOrigin(self.otf, glyph)
bounds = self.glyphBoundingBoxes[glyphName]
top = bounds.yMax if bounds else 0
vmtx[glyphName] = (height, verticalOrigin - top) | python | def setupTable_vmtx(self):
"""
Make the vmtx table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "vmtx" not in self.tables:
return
self.otf["vmtx"] = vmtx = newTable("vmtx")
vmtx.metrics = {}
for glyphName, glyph in self.allGlyphs.items():
height = otRound(glyph.height)
if height < 0:
raise ValueError(
"The height should not be negative: '%s'" % (glyphName))
verticalOrigin = _getVerticalOrigin(self.otf, glyph)
bounds = self.glyphBoundingBoxes[glyphName]
top = bounds.yMax if bounds else 0
vmtx[glyphName] = (height, verticalOrigin - top) | [
"def",
"setupTable_vmtx",
"(",
"self",
")",
":",
"if",
"\"vmtx\"",
"not",
"in",
"self",
".",
"tables",
":",
"return",
"self",
".",
"otf",
"[",
"\"vmtx\"",
"]",
"=",
"vmtx",
"=",
"newTable",
"(",
"\"vmtx\"",
")",
"vmtx",
".",
"metrics",
"=",
"{",
"}",... | Make the vmtx table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired. | [
"Make",
"the",
"vmtx",
"table",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L739-L760 | train | 24,109 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.setupTable_VORG | def setupTable_VORG(self):
"""
Make the VORG table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "VORG" not in self.tables:
return
self.otf["VORG"] = vorg = newTable("VORG")
vorg.majorVersion = 1
vorg.minorVersion = 0
vorg.VOriginRecords = {}
# Find the most frequent verticalOrigin
vorg_count = Counter(_getVerticalOrigin(self.otf, glyph)
for glyph in self.allGlyphs.values())
vorg.defaultVertOriginY = vorg_count.most_common(1)[0][0]
if len(vorg_count) > 1:
for glyphName, glyph in self.allGlyphs.items():
vorg.VOriginRecords[glyphName] = _getVerticalOrigin(
self.otf, glyph)
vorg.numVertOriginYMetrics = len(vorg.VOriginRecords) | python | def setupTable_VORG(self):
"""
Make the VORG table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "VORG" not in self.tables:
return
self.otf["VORG"] = vorg = newTable("VORG")
vorg.majorVersion = 1
vorg.minorVersion = 0
vorg.VOriginRecords = {}
# Find the most frequent verticalOrigin
vorg_count = Counter(_getVerticalOrigin(self.otf, glyph)
for glyph in self.allGlyphs.values())
vorg.defaultVertOriginY = vorg_count.most_common(1)[0][0]
if len(vorg_count) > 1:
for glyphName, glyph in self.allGlyphs.items():
vorg.VOriginRecords[glyphName] = _getVerticalOrigin(
self.otf, glyph)
vorg.numVertOriginYMetrics = len(vorg.VOriginRecords) | [
"def",
"setupTable_VORG",
"(",
"self",
")",
":",
"if",
"\"VORG\"",
"not",
"in",
"self",
".",
"tables",
":",
"return",
"self",
".",
"otf",
"[",
"\"VORG\"",
"]",
"=",
"vorg",
"=",
"newTable",
"(",
"\"VORG\"",
")",
"vorg",
".",
"majorVersion",
"=",
"1",
... | Make the VORG table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired. | [
"Make",
"the",
"VORG",
"table",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L762-L785 | train | 24,110 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.setupTable_post | def setupTable_post(self):
"""
Make the post table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "post" not in self.tables:
return
self.otf["post"] = post = newTable("post")
font = self.ufo
post.formatType = 3.0
# italic angle
italicAngle = getAttrWithFallback(font.info, "italicAngle")
post.italicAngle = italicAngle
# underline
underlinePosition = getAttrWithFallback(font.info, "postscriptUnderlinePosition")
post.underlinePosition = otRound(underlinePosition)
underlineThickness = getAttrWithFallback(font.info, "postscriptUnderlineThickness")
post.underlineThickness = otRound(underlineThickness)
post.isFixedPitch = getAttrWithFallback(font.info, "postscriptIsFixedPitch")
# misc
post.minMemType42 = 0
post.maxMemType42 = 0
post.minMemType1 = 0
post.maxMemType1 = 0 | python | def setupTable_post(self):
"""
Make the post table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "post" not in self.tables:
return
self.otf["post"] = post = newTable("post")
font = self.ufo
post.formatType = 3.0
# italic angle
italicAngle = getAttrWithFallback(font.info, "italicAngle")
post.italicAngle = italicAngle
# underline
underlinePosition = getAttrWithFallback(font.info, "postscriptUnderlinePosition")
post.underlinePosition = otRound(underlinePosition)
underlineThickness = getAttrWithFallback(font.info, "postscriptUnderlineThickness")
post.underlineThickness = otRound(underlineThickness)
post.isFixedPitch = getAttrWithFallback(font.info, "postscriptIsFixedPitch")
# misc
post.minMemType42 = 0
post.maxMemType42 = 0
post.minMemType1 = 0
post.maxMemType1 = 0 | [
"def",
"setupTable_post",
"(",
"self",
")",
":",
"if",
"\"post\"",
"not",
"in",
"self",
".",
"tables",
":",
"return",
"self",
".",
"otf",
"[",
"\"post\"",
"]",
"=",
"post",
"=",
"newTable",
"(",
"\"post\"",
")",
"font",
"=",
"self",
".",
"ufo",
"post... | Make the post table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired. | [
"Make",
"the",
"post",
"table",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L798-L825 | train | 24,111 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | BaseOutlineCompiler.importTTX | def importTTX(self):
"""
Merge TTX files from data directory "com.github.fonttools.ttx"
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired.
"""
import os
import re
prefix = "com.github.fonttools.ttx"
sfntVersionRE = re.compile('(^<ttFont\s+)(sfntVersion=".*"\s+)(.*>$)',
flags=re.MULTILINE)
if not hasattr(self.ufo, "data"):
return
if not self.ufo.data.fileNames:
return
for path in self.ufo.data.fileNames:
foldername, filename = os.path.split(path)
if (foldername == prefix and filename.endswith(".ttx")):
ttx = self.ufo.data[path].decode('utf-8')
# strip 'sfntVersion' attribute from ttFont element,
# if present, to avoid overwriting the current value
ttx = sfntVersionRE.sub(r'\1\3', ttx)
fp = BytesIO(ttx.encode('utf-8'))
self.otf.importXML(fp) | python | def importTTX(self):
"""
Merge TTX files from data directory "com.github.fonttools.ttx"
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired.
"""
import os
import re
prefix = "com.github.fonttools.ttx"
sfntVersionRE = re.compile('(^<ttFont\s+)(sfntVersion=".*"\s+)(.*>$)',
flags=re.MULTILINE)
if not hasattr(self.ufo, "data"):
return
if not self.ufo.data.fileNames:
return
for path in self.ufo.data.fileNames:
foldername, filename = os.path.split(path)
if (foldername == prefix and filename.endswith(".ttx")):
ttx = self.ufo.data[path].decode('utf-8')
# strip 'sfntVersion' attribute from ttFont element,
# if present, to avoid overwriting the current value
ttx = sfntVersionRE.sub(r'\1\3', ttx)
fp = BytesIO(ttx.encode('utf-8'))
self.otf.importXML(fp) | [
"def",
"importTTX",
"(",
"self",
")",
":",
"import",
"os",
"import",
"re",
"prefix",
"=",
"\"com.github.fonttools.ttx\"",
"sfntVersionRE",
"=",
"re",
".",
"compile",
"(",
"'(^<ttFont\\s+)(sfntVersion=\".*\"\\s+)(.*>$)'",
",",
"flags",
"=",
"re",
".",
"MULTILINE",
... | Merge TTX files from data directory "com.github.fonttools.ttx"
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired. | [
"Merge",
"TTX",
"files",
"from",
"data",
"directory",
"com",
".",
"github",
".",
"fonttools",
".",
"ttx"
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L837-L863 | train | 24,112 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | OutlineTTFCompiler.setupTable_post | def setupTable_post(self):
"""Make a format 2 post table with the compiler's glyph order."""
super(OutlineTTFCompiler, self).setupTable_post()
if "post" not in self.otf:
return
post = self.otf["post"]
post.formatType = 2.0
post.extraNames = []
post.mapping = {}
post.glyphOrder = self.glyphOrder | python | def setupTable_post(self):
"""Make a format 2 post table with the compiler's glyph order."""
super(OutlineTTFCompiler, self).setupTable_post()
if "post" not in self.otf:
return
post = self.otf["post"]
post.formatType = 2.0
post.extraNames = []
post.mapping = {}
post.glyphOrder = self.glyphOrder | [
"def",
"setupTable_post",
"(",
"self",
")",
":",
"super",
"(",
"OutlineTTFCompiler",
",",
"self",
")",
".",
"setupTable_post",
"(",
")",
"if",
"\"post\"",
"not",
"in",
"self",
".",
"otf",
":",
"return",
"post",
"=",
"self",
".",
"otf",
"[",
"\"post\"",
... | Make a format 2 post table with the compiler's glyph order. | [
"Make",
"a",
"format",
"2",
"post",
"table",
"with",
"the",
"compiler",
"s",
"glyph",
"order",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L1143-L1153 | train | 24,113 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | OutlineTTFCompiler.setupTable_glyf | def setupTable_glyf(self):
"""Make the glyf table."""
if not {"glyf", "loca"}.issubset(self.tables):
return
self.otf["loca"] = newTable("loca")
self.otf["glyf"] = glyf = newTable("glyf")
glyf.glyphs = {}
glyf.glyphOrder = self.glyphOrder
hmtx = self.otf.get("hmtx")
allGlyphs = self.allGlyphs
for name in self.glyphOrder:
glyph = allGlyphs[name]
pen = TTGlyphPen(allGlyphs)
try:
glyph.draw(pen)
except NotImplementedError:
logger.error("%r has invalid curve format; skipped", name)
ttGlyph = Glyph()
else:
ttGlyph = pen.glyph()
if (
ttGlyph.isComposite()
and hmtx is not None
and self.autoUseMyMetrics
):
self.autoUseMyMetrics(ttGlyph, name, hmtx)
glyf[name] = ttGlyph | python | def setupTable_glyf(self):
"""Make the glyf table."""
if not {"glyf", "loca"}.issubset(self.tables):
return
self.otf["loca"] = newTable("loca")
self.otf["glyf"] = glyf = newTable("glyf")
glyf.glyphs = {}
glyf.glyphOrder = self.glyphOrder
hmtx = self.otf.get("hmtx")
allGlyphs = self.allGlyphs
for name in self.glyphOrder:
glyph = allGlyphs[name]
pen = TTGlyphPen(allGlyphs)
try:
glyph.draw(pen)
except NotImplementedError:
logger.error("%r has invalid curve format; skipped", name)
ttGlyph = Glyph()
else:
ttGlyph = pen.glyph()
if (
ttGlyph.isComposite()
and hmtx is not None
and self.autoUseMyMetrics
):
self.autoUseMyMetrics(ttGlyph, name, hmtx)
glyf[name] = ttGlyph | [
"def",
"setupTable_glyf",
"(",
"self",
")",
":",
"if",
"not",
"{",
"\"glyf\"",
",",
"\"loca\"",
"}",
".",
"issubset",
"(",
"self",
".",
"tables",
")",
":",
"return",
"self",
".",
"otf",
"[",
"\"loca\"",
"]",
"=",
"newTable",
"(",
"\"loca\"",
")",
"se... | Make the glyf table. | [
"Make",
"the",
"glyf",
"table",
"."
] | 915b986558e87bee288765d9218cc1cd4ebf7f4c | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L1160-L1188 | train | 24,114 |
quadrismegistus/prosodic | prosodic/dicts/en/syllabify.py | loadLanguage | def loadLanguage(filename) :
'''This function loads up a language configuration file and returns
the configuration to be passed to the syllabify function.'''
L = { "consonants" : [], "vowels" : [], "onsets" : [] }
f = open(filename, "r")
section = None
for line in f :
line = line.strip()
if line in ("[consonants]", "[vowels]", "[onsets]") :
section = line[1:-1]
elif section == None :
raise ValueError, "File must start with a section header such as [consonants]."
elif not section in L :
raise ValueError, "Invalid section: " + section
else :
L[section].append(line)
for section in "consonants", "vowels", "onsets" :
if len(L[section]) == 0 :
raise ValueError, "File does not contain any consonants, vowels, or onsets."
return L | python | def loadLanguage(filename) :
'''This function loads up a language configuration file and returns
the configuration to be passed to the syllabify function.'''
L = { "consonants" : [], "vowels" : [], "onsets" : [] }
f = open(filename, "r")
section = None
for line in f :
line = line.strip()
if line in ("[consonants]", "[vowels]", "[onsets]") :
section = line[1:-1]
elif section == None :
raise ValueError, "File must start with a section header such as [consonants]."
elif not section in L :
raise ValueError, "Invalid section: " + section
else :
L[section].append(line)
for section in "consonants", "vowels", "onsets" :
if len(L[section]) == 0 :
raise ValueError, "File does not contain any consonants, vowels, or onsets."
return L | [
"def",
"loadLanguage",
"(",
"filename",
")",
":",
"L",
"=",
"{",
"\"consonants\"",
":",
"[",
"]",
",",
"\"vowels\"",
":",
"[",
"]",
",",
"\"onsets\"",
":",
"[",
"]",
"}",
"f",
"=",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"section",
"=",
"None",... | This function loads up a language configuration file and returns
the configuration to be passed to the syllabify function. | [
"This",
"function",
"loads",
"up",
"a",
"language",
"configuration",
"file",
"and",
"returns",
"the",
"configuration",
"to",
"be",
"passed",
"to",
"the",
"syllabify",
"function",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/dicts/en/syllabify.py#L56-L79 | train | 24,115 |
quadrismegistus/prosodic | prosodic/dicts/en/syllabify.py | stringify | def stringify(syllables) :
'''This function takes a syllabification returned by syllabify and
turns it into a string, with phonemes spearated by spaces and
syllables spearated by periods.'''
ret = []
for syl in syllables :
stress, onset, nucleus, coda = syl
if stress != None and len(nucleus) != 0 :
nucleus[0] += str(stress)
ret.append(" ".join(onset + nucleus + coda))
return " . ".join(ret) | python | def stringify(syllables) :
'''This function takes a syllabification returned by syllabify and
turns it into a string, with phonemes spearated by spaces and
syllables spearated by periods.'''
ret = []
for syl in syllables :
stress, onset, nucleus, coda = syl
if stress != None and len(nucleus) != 0 :
nucleus[0] += str(stress)
ret.append(" ".join(onset + nucleus + coda))
return " . ".join(ret) | [
"def",
"stringify",
"(",
"syllables",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"syl",
"in",
"syllables",
":",
"stress",
",",
"onset",
",",
"nucleus",
",",
"coda",
"=",
"syl",
"if",
"stress",
"!=",
"None",
"and",
"len",
"(",
"nucleus",
")",
"!=",
"0",... | This function takes a syllabification returned by syllabify and
turns it into a string, with phonemes spearated by spaces and
syllables spearated by periods. | [
"This",
"function",
"takes",
"a",
"syllabification",
"returned",
"by",
"syllabify",
"and",
"turns",
"it",
"into",
"a",
"string",
"with",
"phonemes",
"spearated",
"by",
"spaces",
"and",
"syllables",
"spearated",
"by",
"periods",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/dicts/en/syllabify.py#L158-L168 | train | 24,116 |
quadrismegistus/prosodic | prosodic/tools.py | slice | def slice(l,num_slices=None,slice_length=None,runts=True,random=False):
"""
Returns a new list of n evenly-sized segments of the original list
"""
if random:
import random
random.shuffle(l)
if not num_slices and not slice_length: return l
if not slice_length: slice_length=int(len(l)/num_slices)
newlist=[l[i:i+slice_length] for i in range(0, len(l), slice_length)]
if runts: return newlist
return [lx for lx in newlist if len(lx)==slice_length] | python | def slice(l,num_slices=None,slice_length=None,runts=True,random=False):
"""
Returns a new list of n evenly-sized segments of the original list
"""
if random:
import random
random.shuffle(l)
if not num_slices and not slice_length: return l
if not slice_length: slice_length=int(len(l)/num_slices)
newlist=[l[i:i+slice_length] for i in range(0, len(l), slice_length)]
if runts: return newlist
return [lx for lx in newlist if len(lx)==slice_length] | [
"def",
"slice",
"(",
"l",
",",
"num_slices",
"=",
"None",
",",
"slice_length",
"=",
"None",
",",
"runts",
"=",
"True",
",",
"random",
"=",
"False",
")",
":",
"if",
"random",
":",
"import",
"random",
"random",
".",
"shuffle",
"(",
"l",
")",
"if",
"n... | Returns a new list of n evenly-sized segments of the original list | [
"Returns",
"a",
"new",
"list",
"of",
"n",
"evenly",
"-",
"sized",
"segments",
"of",
"the",
"original",
"list"
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/tools.py#L3-L14 | train | 24,117 |
quadrismegistus/prosodic | prosodic/entity.py | entity.u2s | def u2s(self,u):
"""Returns an ASCII representation of the Unicode string 'u'."""
try:
return u.encode('utf-8',errors='ignore')
except (UnicodeDecodeError,AttributeError) as e:
try:
return str(u)
except UnicodeEncodeError:
return unicode(u).encode('utf-8',errors='ignore') | python | def u2s(self,u):
"""Returns an ASCII representation of the Unicode string 'u'."""
try:
return u.encode('utf-8',errors='ignore')
except (UnicodeDecodeError,AttributeError) as e:
try:
return str(u)
except UnicodeEncodeError:
return unicode(u).encode('utf-8',errors='ignore') | [
"def",
"u2s",
"(",
"self",
",",
"u",
")",
":",
"try",
":",
"return",
"u",
".",
"encode",
"(",
"'utf-8'",
",",
"errors",
"=",
"'ignore'",
")",
"except",
"(",
"UnicodeDecodeError",
",",
"AttributeError",
")",
"as",
"e",
":",
"try",
":",
"return",
"str"... | Returns an ASCII representation of the Unicode string 'u'. | [
"Returns",
"an",
"ASCII",
"representation",
"of",
"the",
"Unicode",
"string",
"u",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L217-L226 | train | 24,118 |
quadrismegistus/prosodic | prosodic/entity.py | entity.wordtokens | def wordtokens(self,include_punct=True):
"""Returns a list of this object's Words in order of their appearance.
Set flattenList to False to receive a list of lists of Words."""
ws=self.ents('WordToken')
if not include_punct: return [w for w in ws if not w.is_punct]
return ws | python | def wordtokens(self,include_punct=True):
"""Returns a list of this object's Words in order of their appearance.
Set flattenList to False to receive a list of lists of Words."""
ws=self.ents('WordToken')
if not include_punct: return [w for w in ws if not w.is_punct]
return ws | [
"def",
"wordtokens",
"(",
"self",
",",
"include_punct",
"=",
"True",
")",
":",
"ws",
"=",
"self",
".",
"ents",
"(",
"'WordToken'",
")",
"if",
"not",
"include_punct",
":",
"return",
"[",
"w",
"for",
"w",
"in",
"ws",
"if",
"not",
"w",
".",
"is_punct",
... | Returns a list of this object's Words in order of their appearance.
Set flattenList to False to receive a list of lists of Words. | [
"Returns",
"a",
"list",
"of",
"this",
"object",
"s",
"Words",
"in",
"order",
"of",
"their",
"appearance",
".",
"Set",
"flattenList",
"to",
"False",
"to",
"receive",
"a",
"list",
"of",
"lists",
"of",
"Words",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L387-L392 | train | 24,119 |
quadrismegistus/prosodic | prosodic/entity.py | entity.dir | def dir(self,methods=True,showall=True):
"""Show this object's attributes and methods."""
import inspect
#print "[attributes]"
for k,v in sorted(self.__dict__.items()):
if k.startswith("_"): continue
print makeminlength("."+k,being.linelen),"\t",v
if not methods:
return
entmethods=dir(entity)
print
#print "[methods]"
for x in [x for x in dir(self) if ("bound method "+self.classname() in str(getattr(self,x))) and not x.startswith("_")]:
if (not showall) and (x in entmethods): continue
attr=getattr(self,x)
#print attr.__dict__
#print dir(attr)
#doc=inspect.getdoc(attr)
doc = attr.__doc__
if not doc:
doc=""
#else:
# docsplit=[z for z in doc.replace("\r","\n").split("\n") if z]
# if len(docsplit)>1:
# doc = docsplit[0] + "\n" + makeminlength(" ",being.linelen) + "\n".join( makeminlength(" ",being.linelen)+"\t"+z for z in docsplit[1:])
# else:
# doc = docsplit[0]
y=describe_func(attr)
if not y:
y=""
else:
y=", ".join(a+"="+str(b) for (a,b) in y)
print makeminlength("."+x+"("+y+")",being.linelen),"\t", doc
if showall: print | python | def dir(self,methods=True,showall=True):
"""Show this object's attributes and methods."""
import inspect
#print "[attributes]"
for k,v in sorted(self.__dict__.items()):
if k.startswith("_"): continue
print makeminlength("."+k,being.linelen),"\t",v
if not methods:
return
entmethods=dir(entity)
print
#print "[methods]"
for x in [x for x in dir(self) if ("bound method "+self.classname() in str(getattr(self,x))) and not x.startswith("_")]:
if (not showall) and (x in entmethods): continue
attr=getattr(self,x)
#print attr.__dict__
#print dir(attr)
#doc=inspect.getdoc(attr)
doc = attr.__doc__
if not doc:
doc=""
#else:
# docsplit=[z for z in doc.replace("\r","\n").split("\n") if z]
# if len(docsplit)>1:
# doc = docsplit[0] + "\n" + makeminlength(" ",being.linelen) + "\n".join( makeminlength(" ",being.linelen)+"\t"+z for z in docsplit[1:])
# else:
# doc = docsplit[0]
y=describe_func(attr)
if not y:
y=""
else:
y=", ".join(a+"="+str(b) for (a,b) in y)
print makeminlength("."+x+"("+y+")",being.linelen),"\t", doc
if showall: print | [
"def",
"dir",
"(",
"self",
",",
"methods",
"=",
"True",
",",
"showall",
"=",
"True",
")",
":",
"import",
"inspect",
"#print \"[attributes]\"",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
")",
":",
"if",... | Show this object's attributes and methods. | [
"Show",
"this",
"object",
"s",
"attributes",
"and",
"methods",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L433-L472 | train | 24,120 |
quadrismegistus/prosodic | prosodic/entity.py | entity.makeBubbleChart | def makeBubbleChart(self,posdict,name,stattup=None):
"""Returns HTML for a bubble chart of the positin dictionary."""
xname=[x for x in name.split(".") if x.startswith("X_")][0]
yname=[x for x in name.split(".") if x.startswith("Y_")][0]
#elsename=name.replace(xname,'').replace(yname,'').replace('..','.').replace('..','.')
o='<div id="'+name+'"><h2>'+name+'</h2>'
if stattup:
cc=stattup[0]
p=stattup[1]
o+='<h3>corr.coef='+str(cc)+' / p-value='+str(p)+'</h3>'
o+='<br/><script type="text/javascript">\nvar myChart = new Chart.Bubble("'+name+'", {\nwidth: 400,\nheight: 400,\n bubbleSize: 10,\nxlabel:"'+xname+'",\nylabel:"'+yname+'"});\n'
for posnum,xydict in posdict.items():
x_avg,x_std=mean_stdev(xydict['x'])
y_avg,y_std=mean_stdev(xydict['y'])
z=1/(x_std+y_std)
o+='myChart.addBubble('+str(x_avg*100)+', '+str(y_avg*100)+', '+str(z)+', "#666", "'+str(posnum+1)+' [%'+str(x_avg*100)[0:5]+', %'+str(y_avg*100)[0:5]+']");\n'
o+='myChart.redraw();\n</script>\n</div>'
return o | python | def makeBubbleChart(self,posdict,name,stattup=None):
"""Returns HTML for a bubble chart of the positin dictionary."""
xname=[x for x in name.split(".") if x.startswith("X_")][0]
yname=[x for x in name.split(".") if x.startswith("Y_")][0]
#elsename=name.replace(xname,'').replace(yname,'').replace('..','.').replace('..','.')
o='<div id="'+name+'"><h2>'+name+'</h2>'
if stattup:
cc=stattup[0]
p=stattup[1]
o+='<h3>corr.coef='+str(cc)+' / p-value='+str(p)+'</h3>'
o+='<br/><script type="text/javascript">\nvar myChart = new Chart.Bubble("'+name+'", {\nwidth: 400,\nheight: 400,\n bubbleSize: 10,\nxlabel:"'+xname+'",\nylabel:"'+yname+'"});\n'
for posnum,xydict in posdict.items():
x_avg,x_std=mean_stdev(xydict['x'])
y_avg,y_std=mean_stdev(xydict['y'])
z=1/(x_std+y_std)
o+='myChart.addBubble('+str(x_avg*100)+', '+str(y_avg*100)+', '+str(z)+', "#666", "'+str(posnum+1)+' [%'+str(x_avg*100)[0:5]+', %'+str(y_avg*100)[0:5]+']");\n'
o+='myChart.redraw();\n</script>\n</div>'
return o | [
"def",
"makeBubbleChart",
"(",
"self",
",",
"posdict",
",",
"name",
",",
"stattup",
"=",
"None",
")",
":",
"xname",
"=",
"[",
"x",
"for",
"x",
"in",
"name",
".",
"split",
"(",
"\".\"",
")",
"if",
"x",
".",
"startswith",
"(",
"\"X_\"",
")",
"]",
"... | Returns HTML for a bubble chart of the positin dictionary. | [
"Returns",
"HTML",
"for",
"a",
"bubble",
"chart",
"of",
"the",
"positin",
"dictionary",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L790-L816 | train | 24,121 |
quadrismegistus/prosodic | prosodic/entity.py | entity.getName | def getName(self):
"""Return a Name string for this object."""
name=self.findattr('name')
if not name:
name="_directinput_"
if self.classname().lower()=="line":
name+="."+str(self).replace(" ","_").lower()
else:
name=name.replace('.txt','')
while name.startswith("."):
name=name[1:]
return name | python | def getName(self):
"""Return a Name string for this object."""
name=self.findattr('name')
if not name:
name="_directinput_"
if self.classname().lower()=="line":
name+="."+str(self).replace(" ","_").lower()
else:
name=name.replace('.txt','')
while name.startswith("."):
name=name[1:]
return name | [
"def",
"getName",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"findattr",
"(",
"'name'",
")",
"if",
"not",
"name",
":",
"name",
"=",
"\"_directinput_\"",
"if",
"self",
".",
"classname",
"(",
")",
".",
"lower",
"(",
")",
"==",
"\"line\"",
":",
... | Return a Name string for this object. | [
"Return",
"a",
"Name",
"string",
"for",
"this",
"object",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L956-L970 | train | 24,122 |
quadrismegistus/prosodic | prosodic/entity.py | entity.scansion_prepare | def scansion_prepare(self,meter=None,conscious=False):
"""Print out header column for line-scansions for a given meter. """
import prosodic
config=prosodic.config
if not meter:
if not hasattr(self,'_Text__bestparses'): return
x=getattr(self,'_Text__bestparses')
if not x.keys(): return
meter=x.keys()[0]
ckeys="\t".join(sorted([str(x) for x in meter.constraints]))
self.om("\t".join([makeminlength(str("text"),config['linelen']), makeminlength(str("parse"),config['linelen']),"meter","num_parses","num_viols","score_viols",ckeys]),conscious=conscious) | python | def scansion_prepare(self,meter=None,conscious=False):
"""Print out header column for line-scansions for a given meter. """
import prosodic
config=prosodic.config
if not meter:
if not hasattr(self,'_Text__bestparses'): return
x=getattr(self,'_Text__bestparses')
if not x.keys(): return
meter=x.keys()[0]
ckeys="\t".join(sorted([str(x) for x in meter.constraints]))
self.om("\t".join([makeminlength(str("text"),config['linelen']), makeminlength(str("parse"),config['linelen']),"meter","num_parses","num_viols","score_viols",ckeys]),conscious=conscious) | [
"def",
"scansion_prepare",
"(",
"self",
",",
"meter",
"=",
"None",
",",
"conscious",
"=",
"False",
")",
":",
"import",
"prosodic",
"config",
"=",
"prosodic",
".",
"config",
"if",
"not",
"meter",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_Text__bes... | Print out header column for line-scansions for a given meter. | [
"Print",
"out",
"header",
"column",
"for",
"line",
"-",
"scansions",
"for",
"a",
"given",
"meter",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L1138-L1150 | train | 24,123 |
quadrismegistus/prosodic | prosodic/entity.py | entity.report | def report(self,meter=None,include_bounded=False,reverse=True):
""" Print all parses and their violations in a structured format. """
ReportStr = ''
if not meter:
from Meter import Meter
meter=Meter.genDefault()
if (hasattr(self,'allParses')):
self.om(unicode(self))
allparses=self.allParses(meter=meter,include_bounded=include_bounded)
numallparses=len(allparses)
#allparses = reversed(allparses) if reverse else allparses
for pi,parseList in enumerate(allparses):
line=self.iparse2line(pi).txt
#parseList.sort(key = lambda P: P.score())
hdr="\n\n"+'='*30+'\n[line #'+str(pi+1)+' of '+str(numallparses)+']: '+line+'\n\n\t'
ftr='='*30+'\n'
ReportStr+=self.om(hdr+meter.printParses(parseList,reverse=reverse).replace('\n','\n\t')[:-1]+ftr,conscious=False)
else:
for child in self.children:
if type(child)==type([]): continue
ReportStr+=child.report()
return ReportStr | python | def report(self,meter=None,include_bounded=False,reverse=True):
""" Print all parses and their violations in a structured format. """
ReportStr = ''
if not meter:
from Meter import Meter
meter=Meter.genDefault()
if (hasattr(self,'allParses')):
self.om(unicode(self))
allparses=self.allParses(meter=meter,include_bounded=include_bounded)
numallparses=len(allparses)
#allparses = reversed(allparses) if reverse else allparses
for pi,parseList in enumerate(allparses):
line=self.iparse2line(pi).txt
#parseList.sort(key = lambda P: P.score())
hdr="\n\n"+'='*30+'\n[line #'+str(pi+1)+' of '+str(numallparses)+']: '+line+'\n\n\t'
ftr='='*30+'\n'
ReportStr+=self.om(hdr+meter.printParses(parseList,reverse=reverse).replace('\n','\n\t')[:-1]+ftr,conscious=False)
else:
for child in self.children:
if type(child)==type([]): continue
ReportStr+=child.report()
return ReportStr | [
"def",
"report",
"(",
"self",
",",
"meter",
"=",
"None",
",",
"include_bounded",
"=",
"False",
",",
"reverse",
"=",
"True",
")",
":",
"ReportStr",
"=",
"''",
"if",
"not",
"meter",
":",
"from",
"Meter",
"import",
"Meter",
"meter",
"=",
"Meter",
".",
"... | Print all parses and their violations in a structured format. | [
"Print",
"all",
"parses",
"and",
"their",
"violations",
"in",
"a",
"structured",
"format",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L1168-L1191 | train | 24,124 |
quadrismegistus/prosodic | prosodic/entity.py | entity.tree | def tree(self,offset=0,prefix_inherited="",nofeatsplease=['Phoneme']):
"""Print a tree-structure of this object's phonological representation."""
tree = ""
numchild=0
for child in self.children:
if type(child)==type([]):
child=child[0]
numchild+=1
classname=child.classname()
if classname=="Word":
tree+="\n\n"
elif classname=="Line":
tree+="\n\n\n"
elif classname=="Stanza":
tree+="\n\n\n\n"
if offset!=0:
tree+="\n"
for i in range(0,offset):
tree+=" "
#if not len(child.feats):
# tree+=" "
tree+="|"
tree+="\n"
newline=""
for i in range(0,offset):
newline+=" "
newline+="|"
cname=""
for letter in classname:
if letter==letter.upper():
cname+=letter
prefix=prefix_inherited+cname+str(numchild) + "."
newline+="-----| ("+prefix[:-1]+") <"+classname+">"
if child.isBroken():
newline+="<<broken>>"
else:
string=self.u2s(child)
if (not "<" in string):
newline=makeminlength(newline,99)
newline+="["+string+"]"
elif string[0]!="<":
newline+="\t"+string
if len(child.feats):
if (not child.classname() in nofeatsplease):
for k,v in sorted(child.feats.items()):
if v==None:
continue
newline+="\n"
for i in range(0,offset+1):
newline+=" "
newline+="| "
newline+=self.showFeat(k,v)
tree+=newline
tree+=child.tree(offset+1,prefix)
return tree | python | def tree(self,offset=0,prefix_inherited="",nofeatsplease=['Phoneme']):
"""Print a tree-structure of this object's phonological representation."""
tree = ""
numchild=0
for child in self.children:
if type(child)==type([]):
child=child[0]
numchild+=1
classname=child.classname()
if classname=="Word":
tree+="\n\n"
elif classname=="Line":
tree+="\n\n\n"
elif classname=="Stanza":
tree+="\n\n\n\n"
if offset!=0:
tree+="\n"
for i in range(0,offset):
tree+=" "
#if not len(child.feats):
# tree+=" "
tree+="|"
tree+="\n"
newline=""
for i in range(0,offset):
newline+=" "
newline+="|"
cname=""
for letter in classname:
if letter==letter.upper():
cname+=letter
prefix=prefix_inherited+cname+str(numchild) + "."
newline+="-----| ("+prefix[:-1]+") <"+classname+">"
if child.isBroken():
newline+="<<broken>>"
else:
string=self.u2s(child)
if (not "<" in string):
newline=makeminlength(newline,99)
newline+="["+string+"]"
elif string[0]!="<":
newline+="\t"+string
if len(child.feats):
if (not child.classname() in nofeatsplease):
for k,v in sorted(child.feats.items()):
if v==None:
continue
newline+="\n"
for i in range(0,offset+1):
newline+=" "
newline+="| "
newline+=self.showFeat(k,v)
tree+=newline
tree+=child.tree(offset+1,prefix)
return tree | [
"def",
"tree",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"prefix_inherited",
"=",
"\"\"",
",",
"nofeatsplease",
"=",
"[",
"'Phoneme'",
"]",
")",
":",
"tree",
"=",
"\"\"",
"numchild",
"=",
"0",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if"... | Print a tree-structure of this object's phonological representation. | [
"Print",
"a",
"tree",
"-",
"structure",
"of",
"this",
"object",
"s",
"phonological",
"representation",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L1212-L1278 | train | 24,125 |
quadrismegistus/prosodic | prosodic/entity.py | entity.search | def search(self, searchTerm):
"""Returns objects matching the query."""
if type(searchTerm)==type(''):
searchTerm=SearchTerm(searchTerm)
if searchTerm not in self.featpaths:
matches = None
if searchTerm.type != None and searchTerm.type != self.classname():
matches = self._searchInChildren(searchTerm)
elif searchTerm.isAtomic():
matches = self._searchSingleTerm(searchTerm)
else:
matches = self._searchMultipleTerms(searchTerm)
if matches == True:
matches = [self]
if matches == False:
matches = []
self.featpaths[searchTerm] = matches
return self.featpaths[searchTerm] | python | def search(self, searchTerm):
"""Returns objects matching the query."""
if type(searchTerm)==type(''):
searchTerm=SearchTerm(searchTerm)
if searchTerm not in self.featpaths:
matches = None
if searchTerm.type != None and searchTerm.type != self.classname():
matches = self._searchInChildren(searchTerm)
elif searchTerm.isAtomic():
matches = self._searchSingleTerm(searchTerm)
else:
matches = self._searchMultipleTerms(searchTerm)
if matches == True:
matches = [self]
if matches == False:
matches = []
self.featpaths[searchTerm] = matches
return self.featpaths[searchTerm] | [
"def",
"search",
"(",
"self",
",",
"searchTerm",
")",
":",
"if",
"type",
"(",
"searchTerm",
")",
"==",
"type",
"(",
"''",
")",
":",
"searchTerm",
"=",
"SearchTerm",
"(",
"searchTerm",
")",
"if",
"searchTerm",
"not",
"in",
"self",
".",
"featpaths",
":",... | Returns objects matching the query. | [
"Returns",
"objects",
"matching",
"the",
"query",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L1501-L1520 | train | 24,126 |
quadrismegistus/prosodic | prosodic/Text.py | Text.stats_positions | def stats_positions(self,meter=None,all_parses=False):
"""Produce statistics from the parser"""
"""Positions
All feats of slots
All constraint violations
"""
parses = self.allParses(meter=meter) if all_parses else [[parse] for parse in self.bestParses(meter=meter)]
dx={}
for parselist in parses:
for parse in parselist:
if not parse: continue
slot_i=0
for pos in parse.positions:
for slot in pos.slots:
slot_i+=1
feat_dicts = [slot.feats, pos.constraintScores, pos.feats]
for feat_dict in feat_dicts:
for k,v in feat_dict.items():
dk = (slot_i,str(k))
if not dk in dx: dx[dk]=[]
dx[dk]+=[v]
def _writegen():
for ((slot_i,k),l) in sorted(dx.items()):
l2=[]
for x in l:
if type(x)==bool:
x=1 if x else 0
elif type(x)==type(None):
x=0
elif type(x) in [str,unicode]:
continue
else:
x=float(x)
if x>1: x=1
l2+=[x]
#print k, l2
#try:
if not l2: continue
avg=sum(l2) / float(len(l2))
count=sum(l2)
chances=len(l2)
#except TypeError:
# continue
odx={'slot_num':slot_i, 'statistic':k, 'average':avg, 'count':count, 'chances':chances, 'text':self.name}
odx['header']=['slot_num', 'statistic','count','chances','average']
#print odx
yield odx
name=self.name.replace('.txt','')
ofn=os.path.join(self.dir_results, 'stats','texts',name, name+'.positions.csv')
#print ofn
if not os.path.exists(os.path.split(ofn)[0]): os.makedirs(os.path.split(ofn)[0])
for dx in writegengen(ofn, _writegen):
yield dx
print '>> saved:',ofn | python | def stats_positions(self,meter=None,all_parses=False):
"""Produce statistics from the parser"""
"""Positions
All feats of slots
All constraint violations
"""
parses = self.allParses(meter=meter) if all_parses else [[parse] for parse in self.bestParses(meter=meter)]
dx={}
for parselist in parses:
for parse in parselist:
if not parse: continue
slot_i=0
for pos in parse.positions:
for slot in pos.slots:
slot_i+=1
feat_dicts = [slot.feats, pos.constraintScores, pos.feats]
for feat_dict in feat_dicts:
for k,v in feat_dict.items():
dk = (slot_i,str(k))
if not dk in dx: dx[dk]=[]
dx[dk]+=[v]
def _writegen():
for ((slot_i,k),l) in sorted(dx.items()):
l2=[]
for x in l:
if type(x)==bool:
x=1 if x else 0
elif type(x)==type(None):
x=0
elif type(x) in [str,unicode]:
continue
else:
x=float(x)
if x>1: x=1
l2+=[x]
#print k, l2
#try:
if not l2: continue
avg=sum(l2) / float(len(l2))
count=sum(l2)
chances=len(l2)
#except TypeError:
# continue
odx={'slot_num':slot_i, 'statistic':k, 'average':avg, 'count':count, 'chances':chances, 'text':self.name}
odx['header']=['slot_num', 'statistic','count','chances','average']
#print odx
yield odx
name=self.name.replace('.txt','')
ofn=os.path.join(self.dir_results, 'stats','texts',name, name+'.positions.csv')
#print ofn
if not os.path.exists(os.path.split(ofn)[0]): os.makedirs(os.path.split(ofn)[0])
for dx in writegengen(ofn, _writegen):
yield dx
print '>> saved:',ofn | [
"def",
"stats_positions",
"(",
"self",
",",
"meter",
"=",
"None",
",",
"all_parses",
"=",
"False",
")",
":",
"\"\"\"Positions\n\t\tAll feats of slots\n\t\tAll constraint violations\n\n\n\t\t\"\"\"",
"parses",
"=",
"self",
".",
"allParses",
"(",
"meter",
"=",
"meter",
... | Produce statistics from the parser | [
"Produce",
"statistics",
"from",
"the",
"parser"
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/Text.py#L191-L256 | train | 24,127 |
quadrismegistus/prosodic | prosodic/Text.py | Text.iparse | def iparse(self,meter=None,num_processes=1,arbiter='Line',line_lim=None):
"""Parse this text metrically, yielding it line by line."""
from Meter import Meter,genDefault,parse_ent,parse_ent_mp
import multiprocessing as mp
meter=self.get_meter(meter)
# set internal attributes
self.__parses[meter.id]=[]
self.__bestparses[meter.id]=[]
self.__boundParses[meter.id]=[]
self.__parsed_ents[meter.id]=[]
lines = self.lines()
lines=lines[:line_lim]
numlines = len(lines)
init=self
ents=self.ents(arbiter)
smax=self.config.get('line_maxsylls',100)
smin=self.config.get('line_minsylls',0)
#print '>> # of lines to parse:',len(ents)
ents = [e for e in ents if e.num_syll >= smin and e.num_syll<=smax]
#print '>> # of lines to parse after applying min/max line settings:',len(ents)
self.scansion_prepare(meter=meter,conscious=True)
numents=len(ents)
#pool=mp.Pool(1)
toprint=self.config['print_to_screen']
objects = [(ent,meter,init,False) for ent in ents]
if num_processes>1:
print '!! MULTIPROCESSING PARSING IS NOT WORKING YET !!'
pool = mp.Pool(num_processes)
jobs = [pool.apply_async(parse_ent_mp,(x,)) for x in objects]
for j in jobs:
print j.get()
yield j.get()
else:
now=time.time()
clock_snum=0
#for ei,ent in enumerate(pool.imap(parse_ent_mp,objects)):
for ei,objectx in enumerate(objects):
clock_snum+=ent.num_syll
if ei and not ei%100:
nownow=time.time()
if self.config['print_to_screen']:
print '>> parsing line #',ei,'of',numents,'lines','[',round(float(clock_snum/(nownow-now)),2),'syllables/second',']'
now=nownow
clock_snum=0
yield parse_ent_mp(objectx)
if self.config['print_to_screen']:
print '>> parsing complete in:',time.time()-now,'seconds' | python | def iparse(self,meter=None,num_processes=1,arbiter='Line',line_lim=None):
"""Parse this text metrically, yielding it line by line."""
from Meter import Meter,genDefault,parse_ent,parse_ent_mp
import multiprocessing as mp
meter=self.get_meter(meter)
# set internal attributes
self.__parses[meter.id]=[]
self.__bestparses[meter.id]=[]
self.__boundParses[meter.id]=[]
self.__parsed_ents[meter.id]=[]
lines = self.lines()
lines=lines[:line_lim]
numlines = len(lines)
init=self
ents=self.ents(arbiter)
smax=self.config.get('line_maxsylls',100)
smin=self.config.get('line_minsylls',0)
#print '>> # of lines to parse:',len(ents)
ents = [e for e in ents if e.num_syll >= smin and e.num_syll<=smax]
#print '>> # of lines to parse after applying min/max line settings:',len(ents)
self.scansion_prepare(meter=meter,conscious=True)
numents=len(ents)
#pool=mp.Pool(1)
toprint=self.config['print_to_screen']
objects = [(ent,meter,init,False) for ent in ents]
if num_processes>1:
print '!! MULTIPROCESSING PARSING IS NOT WORKING YET !!'
pool = mp.Pool(num_processes)
jobs = [pool.apply_async(parse_ent_mp,(x,)) for x in objects]
for j in jobs:
print j.get()
yield j.get()
else:
now=time.time()
clock_snum=0
#for ei,ent in enumerate(pool.imap(parse_ent_mp,objects)):
for ei,objectx in enumerate(objects):
clock_snum+=ent.num_syll
if ei and not ei%100:
nownow=time.time()
if self.config['print_to_screen']:
print '>> parsing line #',ei,'of',numents,'lines','[',round(float(clock_snum/(nownow-now)),2),'syllables/second',']'
now=nownow
clock_snum=0
yield parse_ent_mp(objectx)
if self.config['print_to_screen']:
print '>> parsing complete in:',time.time()-now,'seconds' | [
"def",
"iparse",
"(",
"self",
",",
"meter",
"=",
"None",
",",
"num_processes",
"=",
"1",
",",
"arbiter",
"=",
"'Line'",
",",
"line_lim",
"=",
"None",
")",
":",
"from",
"Meter",
"import",
"Meter",
",",
"genDefault",
",",
"parse_ent",
",",
"parse_ent_mp",
... | Parse this text metrically, yielding it line by line. | [
"Parse",
"this",
"text",
"metrically",
"yielding",
"it",
"line",
"by",
"line",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/Text.py#L468-L523 | train | 24,128 |
quadrismegistus/prosodic | prosodic/Text.py | Text.scansion | def scansion(self,meter=None,conscious=False):
"""Print out the parses and their violations in scansion format."""
meter=self.get_meter(meter)
self.scansion_prepare(meter=meter,conscious=conscious)
for line in self.lines():
try:
line.scansion(meter=meter,conscious=conscious)
except AttributeError:
print "!!! Line skipped [Unknown word]:"
print line
print line.words()
print | python | def scansion(self,meter=None,conscious=False):
"""Print out the parses and their violations in scansion format."""
meter=self.get_meter(meter)
self.scansion_prepare(meter=meter,conscious=conscious)
for line in self.lines():
try:
line.scansion(meter=meter,conscious=conscious)
except AttributeError:
print "!!! Line skipped [Unknown word]:"
print line
print line.words()
print | [
"def",
"scansion",
"(",
"self",
",",
"meter",
"=",
"None",
",",
"conscious",
"=",
"False",
")",
":",
"meter",
"=",
"self",
".",
"get_meter",
"(",
"meter",
")",
"self",
".",
"scansion_prepare",
"(",
"meter",
"=",
"meter",
",",
"conscious",
"=",
"conscio... | Print out the parses and their violations in scansion format. | [
"Print",
"out",
"the",
"parses",
"and",
"their",
"violations",
"in",
"scansion",
"format",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/Text.py#L610-L621 | train | 24,129 |
quadrismegistus/prosodic | prosodic/Text.py | Text.allParses | def allParses(self,meter=None,include_bounded=False,one_per_meter=True):
"""Return a list of lists of parses."""
meter=self.get_meter(meter)
try:
parses=self.__parses[meter.id]
if one_per_meter:
toreturn=[]
for _parses in parses:
sofar=set()
_parses2=[]
for _p in _parses:
_pm=_p.str_meter()
if not _pm in sofar:
sofar|={_pm}
if _p.isBounded and _p.boundedBy.str_meter() == _pm:
pass
else:
_parses2+=[_p]
toreturn+=[_parses2]
parses=toreturn
if include_bounded:
boundedParses=self.boundParses(meter)
return [bp+boundp for bp,boundp in zip(toreturn,boundedParses)]
else:
return parses
except (KeyError,IndexError) as e:
return [] | python | def allParses(self,meter=None,include_bounded=False,one_per_meter=True):
"""Return a list of lists of parses."""
meter=self.get_meter(meter)
try:
parses=self.__parses[meter.id]
if one_per_meter:
toreturn=[]
for _parses in parses:
sofar=set()
_parses2=[]
for _p in _parses:
_pm=_p.str_meter()
if not _pm in sofar:
sofar|={_pm}
if _p.isBounded and _p.boundedBy.str_meter() == _pm:
pass
else:
_parses2+=[_p]
toreturn+=[_parses2]
parses=toreturn
if include_bounded:
boundedParses=self.boundParses(meter)
return [bp+boundp for bp,boundp in zip(toreturn,boundedParses)]
else:
return parses
except (KeyError,IndexError) as e:
return [] | [
"def",
"allParses",
"(",
"self",
",",
"meter",
"=",
"None",
",",
"include_bounded",
"=",
"False",
",",
"one_per_meter",
"=",
"True",
")",
":",
"meter",
"=",
"self",
".",
"get_meter",
"(",
"meter",
")",
"try",
":",
"parses",
"=",
"self",
".",
"__parses"... | Return a list of lists of parses. | [
"Return",
"a",
"list",
"of",
"lists",
"of",
"parses",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/Text.py#L628-L658 | train | 24,130 |
quadrismegistus/prosodic | prosodic/Text.py | Text.validlines | def validlines(self):
"""Return all lines within which Prosodic understood all words."""
return [ln for ln in self.lines() if (not ln.isBroken() and not ln.ignoreMe)] | python | def validlines(self):
"""Return all lines within which Prosodic understood all words."""
return [ln for ln in self.lines() if (not ln.isBroken() and not ln.ignoreMe)] | [
"def",
"validlines",
"(",
"self",
")",
":",
"return",
"[",
"ln",
"for",
"ln",
"in",
"self",
".",
"lines",
"(",
")",
"if",
"(",
"not",
"ln",
".",
"isBroken",
"(",
")",
"and",
"not",
"ln",
".",
"ignoreMe",
")",
"]"
] | Return all lines within which Prosodic understood all words. | [
"Return",
"all",
"lines",
"within",
"which",
"Prosodic",
"understood",
"all",
"words",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/Text.py#L843-L846 | train | 24,131 |
bartTC/django-markup | django_markup/markup.py | MarkupFormatter.choices | def choices(self):
"""
Returns the filter list as a tuple. Useful for model choices.
"""
choice_list = getattr(
settings, 'MARKUP_CHOICES', DEFAULT_MARKUP_CHOICES
)
return [(f, self._get_filter_title(f)) for f in choice_list] | python | def choices(self):
"""
Returns the filter list as a tuple. Useful for model choices.
"""
choice_list = getattr(
settings, 'MARKUP_CHOICES', DEFAULT_MARKUP_CHOICES
)
return [(f, self._get_filter_title(f)) for f in choice_list] | [
"def",
"choices",
"(",
"self",
")",
":",
"choice_list",
"=",
"getattr",
"(",
"settings",
",",
"'MARKUP_CHOICES'",
",",
"DEFAULT_MARKUP_CHOICES",
")",
"return",
"[",
"(",
"f",
",",
"self",
".",
"_get_filter_title",
"(",
"f",
")",
")",
"for",
"f",
"in",
"c... | Returns the filter list as a tuple. Useful for model choices. | [
"Returns",
"the",
"filter",
"list",
"as",
"a",
"tuple",
".",
"Useful",
"for",
"model",
"choices",
"."
] | 1c9c0b46373cc5350282407cec82114af80b8ea3 | https://github.com/bartTC/django-markup/blob/1c9c0b46373cc5350282407cec82114af80b8ea3/django_markup/markup.py#L38-L45 | train | 24,132 |
bartTC/django-markup | django_markup/markup.py | MarkupFormatter.unregister | def unregister(self, filter_name):
"""
Unregister a filter from the filter list
"""
if filter_name in self.filter_list:
self.filter_list.pop(filter_name) | python | def unregister(self, filter_name):
"""
Unregister a filter from the filter list
"""
if filter_name in self.filter_list:
self.filter_list.pop(filter_name) | [
"def",
"unregister",
"(",
"self",
",",
"filter_name",
")",
":",
"if",
"filter_name",
"in",
"self",
".",
"filter_list",
":",
"self",
".",
"filter_list",
".",
"pop",
"(",
"filter_name",
")"
] | Unregister a filter from the filter list | [
"Unregister",
"a",
"filter",
"from",
"the",
"filter",
"list"
] | 1c9c0b46373cc5350282407cec82114af80b8ea3 | https://github.com/bartTC/django-markup/blob/1c9c0b46373cc5350282407cec82114af80b8ea3/django_markup/markup.py#L59-L64 | train | 24,133 |
quadrismegistus/prosodic | metricaltree/metricaltree.py | MetricalTree.convert | def convert(cls, tree):
"""
Convert a tree between different subtypes of Tree. ``cls`` determines
which class will be used to encode the new tree.
:type tree: Tree
:param tree: The tree that should be converted.
:return: The new Tree.
"""
if isinstance(tree, Tree):
children = [cls.convert(child) for child in tree]
if isinstance(tree, MetricalTree):
return cls(tree._cat, children, tree._dep, tree._lstress)
elif isinstance(tree, DependencyTree):
return cls(tree._cat, children, tree._dep)
else:
return cls(tree._label, children)
else:
return tree | python | def convert(cls, tree):
"""
Convert a tree between different subtypes of Tree. ``cls`` determines
which class will be used to encode the new tree.
:type tree: Tree
:param tree: The tree that should be converted.
:return: The new Tree.
"""
if isinstance(tree, Tree):
children = [cls.convert(child) for child in tree]
if isinstance(tree, MetricalTree):
return cls(tree._cat, children, tree._dep, tree._lstress)
elif isinstance(tree, DependencyTree):
return cls(tree._cat, children, tree._dep)
else:
return cls(tree._label, children)
else:
return tree | [
"def",
"convert",
"(",
"cls",
",",
"tree",
")",
":",
"if",
"isinstance",
"(",
"tree",
",",
"Tree",
")",
":",
"children",
"=",
"[",
"cls",
".",
"convert",
"(",
"child",
")",
"for",
"child",
"in",
"tree",
"]",
"if",
"isinstance",
"(",
"tree",
",",
... | Convert a tree between different subtypes of Tree. ``cls`` determines
which class will be used to encode the new tree.
:type tree: Tree
:param tree: The tree that should be converted.
:return: The new Tree. | [
"Convert",
"a",
"tree",
"between",
"different",
"subtypes",
"of",
"Tree",
".",
"cls",
"determines",
"which",
"class",
"will",
"be",
"used",
"to",
"encode",
"the",
"new",
"tree",
"."
] | 8af66ed9be40c922d03a0b09bc11c87d2061b618 | https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/metricaltree/metricaltree.py#L377-L396 | train | 24,134 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/models/runtime_raw_extension.py | RuntimeRawExtension.raw | def raw(self, raw):
"""Sets the raw of this RuntimeRawExtension.
Raw is the underlying serialization of this object. # noqa: E501
:param raw: The raw of this RuntimeRawExtension. # noqa: E501
:type: str
"""
if raw is None:
raise ValueError("Invalid value for `raw`, must not be `None`") # noqa: E501
if raw is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', raw): # noqa: E501
raise ValueError(r"Invalid value for `raw`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501
self._raw = raw | python | def raw(self, raw):
"""Sets the raw of this RuntimeRawExtension.
Raw is the underlying serialization of this object. # noqa: E501
:param raw: The raw of this RuntimeRawExtension. # noqa: E501
:type: str
"""
if raw is None:
raise ValueError("Invalid value for `raw`, must not be `None`") # noqa: E501
if raw is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', raw): # noqa: E501
raise ValueError(r"Invalid value for `raw`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501
self._raw = raw | [
"def",
"raw",
"(",
"self",
",",
"raw",
")",
":",
"if",
"raw",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `raw`, must not be `None`\"",
")",
"# noqa: E501",
"if",
"raw",
"is",
"not",
"None",
"and",
"not",
"re",
".",
"search",
"(",
"... | Sets the raw of this RuntimeRawExtension.
Raw is the underlying serialization of this object. # noqa: E501
:param raw: The raw of this RuntimeRawExtension. # noqa: E501
:type: str | [
"Sets",
"the",
"raw",
"of",
"this",
"RuntimeRawExtension",
"."
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/models/runtime_raw_extension.py#L61-L74 | train | 24,135 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/watch/watch.py | Watch.unmarshal_event | def unmarshal_event(self, data: str, response_type):
"""Return the K8s response `data` in JSON format.
"""
js = json.loads(data)
# Make a copy of the original object and save it under the
# `raw_object` key because we will replace the data under `object` with
# a Python native type shortly.
js['raw_object'] = js['object']
# Something went wrong. A typical example would be that the user
# supplied a resource version that was too old. In that case K8s would
# not send a conventional ADDED/DELETED/... event but an error. Turn
# this error into a Python exception to save the user the hassle.
if js['type'].lower() == 'error':
return js
# If possible, compile the JSON response into a Python native response
# type, eg `V1Namespace` or `V1Pod`,`ExtensionsV1beta1Deployment`, ...
if response_type is not None:
js['object'] = self._api_client.deserialize(
response=SimpleNamespace(data=json.dumps(js['raw_object'])),
response_type=response_type
)
# decode and save resource_version to continue watching
if hasattr(js['object'], 'metadata'):
self.resource_version = js['object'].metadata.resource_version
# For custom objects that we don't have model defined, json
# deserialization results in dictionary
elif (isinstance(js['object'], dict) and
'metadata' in js['object'] and
'resourceVersion' in js['object']['metadata']):
self.resource_version = js['object']['metadata']['resourceVersion']
return js | python | def unmarshal_event(self, data: str, response_type):
"""Return the K8s response `data` in JSON format.
"""
js = json.loads(data)
# Make a copy of the original object and save it under the
# `raw_object` key because we will replace the data under `object` with
# a Python native type shortly.
js['raw_object'] = js['object']
# Something went wrong. A typical example would be that the user
# supplied a resource version that was too old. In that case K8s would
# not send a conventional ADDED/DELETED/... event but an error. Turn
# this error into a Python exception to save the user the hassle.
if js['type'].lower() == 'error':
return js
# If possible, compile the JSON response into a Python native response
# type, eg `V1Namespace` or `V1Pod`,`ExtensionsV1beta1Deployment`, ...
if response_type is not None:
js['object'] = self._api_client.deserialize(
response=SimpleNamespace(data=json.dumps(js['raw_object'])),
response_type=response_type
)
# decode and save resource_version to continue watching
if hasattr(js['object'], 'metadata'):
self.resource_version = js['object'].metadata.resource_version
# For custom objects that we don't have model defined, json
# deserialization results in dictionary
elif (isinstance(js['object'], dict) and
'metadata' in js['object'] and
'resourceVersion' in js['object']['metadata']):
self.resource_version = js['object']['metadata']['resourceVersion']
return js | [
"def",
"unmarshal_event",
"(",
"self",
",",
"data",
":",
"str",
",",
"response_type",
")",
":",
"js",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"# Make a copy of the original object and save it under the",
"# `raw_object` key because we will replace the data under `objec... | Return the K8s response `data` in JSON format. | [
"Return",
"the",
"K8s",
"response",
"data",
"in",
"JSON",
"format",
"."
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/watch/watch.py#L67-L105 | train | 24,136 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/watch/watch.py | Watch.stream | def stream(self, func, *args, **kwargs):
"""Watch an API resource and stream the result back via a generator.
:param func: The API function pointer. Any parameter to the function
can be passed after this parameter.
:return: Event object with these keys:
'type': The type of event such as "ADDED", "DELETED", etc.
'raw_object': a dict representing the watched object.
'object': A model representation of raw_object. The name of
model will be determined based on
the func's doc string. If it cannot be determined,
'object' value will be the same as 'raw_object'.
Example:
v1 = kubernetes_asyncio.client.CoreV1Api()
watch = kubernetes_asyncio.watch.Watch()
async for e in watch.stream(v1.list_namespace, timeout_seconds=10):
type = e['type']
object = e['object'] # object is one of type return_type
raw_object = e['raw_object'] # raw_object is a dict
...
if should_stop:
watch.stop()
"""
self.close()
self._stop = False
self.return_type = self.get_return_type(func)
kwargs['watch'] = True
kwargs['_preload_content'] = False
self.func = partial(func, *args, **kwargs)
return self | python | def stream(self, func, *args, **kwargs):
"""Watch an API resource and stream the result back via a generator.
:param func: The API function pointer. Any parameter to the function
can be passed after this parameter.
:return: Event object with these keys:
'type': The type of event such as "ADDED", "DELETED", etc.
'raw_object': a dict representing the watched object.
'object': A model representation of raw_object. The name of
model will be determined based on
the func's doc string. If it cannot be determined,
'object' value will be the same as 'raw_object'.
Example:
v1 = kubernetes_asyncio.client.CoreV1Api()
watch = kubernetes_asyncio.watch.Watch()
async for e in watch.stream(v1.list_namespace, timeout_seconds=10):
type = e['type']
object = e['object'] # object is one of type return_type
raw_object = e['raw_object'] # raw_object is a dict
...
if should_stop:
watch.stop()
"""
self.close()
self._stop = False
self.return_type = self.get_return_type(func)
kwargs['watch'] = True
kwargs['_preload_content'] = False
self.func = partial(func, *args, **kwargs)
return self | [
"def",
"stream",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"close",
"(",
")",
"self",
".",
"_stop",
"=",
"False",
"self",
".",
"return_type",
"=",
"self",
".",
"get_return_type",
"(",
"func",
")",
... | Watch an API resource and stream the result back via a generator.
:param func: The API function pointer. Any parameter to the function
can be passed after this parameter.
:return: Event object with these keys:
'type': The type of event such as "ADDED", "DELETED", etc.
'raw_object': a dict representing the watched object.
'object': A model representation of raw_object. The name of
model will be determined based on
the func's doc string. If it cannot be determined,
'object' value will be the same as 'raw_object'.
Example:
v1 = kubernetes_asyncio.client.CoreV1Api()
watch = kubernetes_asyncio.watch.Watch()
async for e in watch.stream(v1.list_namespace, timeout_seconds=10):
type = e['type']
object = e['object'] # object is one of type return_type
raw_object = e['raw_object'] # raw_object is a dict
...
if should_stop:
watch.stop() | [
"Watch",
"an",
"API",
"resource",
"and",
"stream",
"the",
"result",
"back",
"via",
"a",
"generator",
"."
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/watch/watch.py#L152-L185 | train | 24,137 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/rest.py | RESTResponse.getheader | def getheader(self, name, default=None):
"""Returns a given response header."""
return self.aiohttp_response.headers.get(name, default) | python | def getheader(self, name, default=None):
"""Returns a given response header."""
return self.aiohttp_response.headers.get(name, default) | [
"def",
"getheader",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"aiohttp_response",
".",
"headers",
".",
"get",
"(",
"name",
",",
"default",
")"
] | Returns a given response header. | [
"Returns",
"a",
"given",
"response",
"header",
"."
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/rest.py#L40-L42 | train | 24,138 |
swistakm/graceful | src/graceful/authorization.py | authentication_required | def authentication_required(req, resp, resource, uri_kwargs):
"""Ensure that user is authenticated otherwise return ``401 Unauthorized``.
If request fails to authenticate this authorization hook will also
include list of ``WWW-Athenticate`` challenges.
Args:
req (falcon.Request): the request object.
resp (falcon.Response): the response object.
resource (object): the resource object.
uri_kwargs (dict): keyword arguments from the URI template.
.. versionadded:: 0.4.0
"""
if 'user' not in req.context:
args = ["Unauthorized", "This resource requires authentication"]
# compat: falcon >= 1.0.0 requires the list of challenges
if FALCON_VERSION >= (1, 0, 0):
args.append(req.context.get('challenges', []))
raise HTTPUnauthorized(*args) | python | def authentication_required(req, resp, resource, uri_kwargs):
"""Ensure that user is authenticated otherwise return ``401 Unauthorized``.
If request fails to authenticate this authorization hook will also
include list of ``WWW-Athenticate`` challenges.
Args:
req (falcon.Request): the request object.
resp (falcon.Response): the response object.
resource (object): the resource object.
uri_kwargs (dict): keyword arguments from the URI template.
.. versionadded:: 0.4.0
"""
if 'user' not in req.context:
args = ["Unauthorized", "This resource requires authentication"]
# compat: falcon >= 1.0.0 requires the list of challenges
if FALCON_VERSION >= (1, 0, 0):
args.append(req.context.get('challenges', []))
raise HTTPUnauthorized(*args) | [
"def",
"authentication_required",
"(",
"req",
",",
"resp",
",",
"resource",
",",
"uri_kwargs",
")",
":",
"if",
"'user'",
"not",
"in",
"req",
".",
"context",
":",
"args",
"=",
"[",
"\"Unauthorized\"",
",",
"\"This resource requires authentication\"",
"]",
"# comp... | Ensure that user is authenticated otherwise return ``401 Unauthorized``.
If request fails to authenticate this authorization hook will also
include list of ``WWW-Athenticate`` challenges.
Args:
req (falcon.Request): the request object.
resp (falcon.Response): the response object.
resource (object): the resource object.
uri_kwargs (dict): keyword arguments from the URI template.
.. versionadded:: 0.4.0 | [
"Ensure",
"that",
"user",
"is",
"authenticated",
"otherwise",
"return",
"401",
"Unauthorized",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authorization.py#L22-L43 | train | 24,139 |
swistakm/graceful | src/graceful/fields.py | BaseField.describe | def describe(self, **kwargs):
"""
Describe this field instance for purpose of self-documentation.
Args:
kwargs (dict): dictionary of additional description items for
extending default description
Returns:
dict: dictionary of description items
Suggested way for overriding description fields or extending it with
additional items is calling super class method with new/overriden
fields passed as keyword arguments like following:
.. code-block:: python
class DummyField(BaseField):
def description(self, **kwargs):
super().describe(is_dummy=True, **kwargs)
"""
description = {
'label': self.label,
'details': inspect.cleandoc(self.details),
'type': "list of {}".format(self.type) if self.many else self.type,
'spec': self.spec,
'read_only': self.read_only,
'write_only': self.write_only,
'allow_null': self.allow_null,
}
description.update(kwargs)
return description | python | def describe(self, **kwargs):
"""
Describe this field instance for purpose of self-documentation.
Args:
kwargs (dict): dictionary of additional description items for
extending default description
Returns:
dict: dictionary of description items
Suggested way for overriding description fields or extending it with
additional items is calling super class method with new/overriden
fields passed as keyword arguments like following:
.. code-block:: python
class DummyField(BaseField):
def description(self, **kwargs):
super().describe(is_dummy=True, **kwargs)
"""
description = {
'label': self.label,
'details': inspect.cleandoc(self.details),
'type': "list of {}".format(self.type) if self.many else self.type,
'spec': self.spec,
'read_only': self.read_only,
'write_only': self.write_only,
'allow_null': self.allow_null,
}
description.update(kwargs)
return description | [
"def",
"describe",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"description",
"=",
"{",
"'label'",
":",
"self",
".",
"label",
",",
"'details'",
":",
"inspect",
".",
"cleandoc",
"(",
"self",
".",
"details",
")",
",",
"'type'",
":",
"\"list of {}\"",... | Describe this field instance for purpose of self-documentation.
Args:
kwargs (dict): dictionary of additional description items for
extending default description
Returns:
dict: dictionary of description items
Suggested way for overriding description fields or extending it with
additional items is calling super class method with new/overriden
fields passed as keyword arguments like following:
.. code-block:: python
class DummyField(BaseField):
def description(self, **kwargs):
super().describe(is_dummy=True, **kwargs) | [
"Describe",
"this",
"field",
"instance",
"for",
"purpose",
"of",
"self",
"-",
"documentation",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/fields.py#L134-L166 | train | 24,140 |
swistakm/graceful | src/graceful/fields.py | BoolField.from_representation | def from_representation(self, data):
"""Convert representation value to ``bool`` if it has expected form."""
if data in self._TRUE_VALUES:
return True
elif data in self._FALSE_VALUES:
return False
else:
raise ValueError(
"{type} type value must be one of {values}".format(
type=self.type,
values=self._TRUE_VALUES.union(self._FALSE_VALUES)
)
) | python | def from_representation(self, data):
"""Convert representation value to ``bool`` if it has expected form."""
if data in self._TRUE_VALUES:
return True
elif data in self._FALSE_VALUES:
return False
else:
raise ValueError(
"{type} type value must be one of {values}".format(
type=self.type,
values=self._TRUE_VALUES.union(self._FALSE_VALUES)
)
) | [
"def",
"from_representation",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"in",
"self",
".",
"_TRUE_VALUES",
":",
"return",
"True",
"elif",
"data",
"in",
"self",
".",
"_FALSE_VALUES",
":",
"return",
"False",
"else",
":",
"raise",
"ValueError",
"(",
... | Convert representation value to ``bool`` if it has expected form. | [
"Convert",
"representation",
"value",
"to",
"bool",
"if",
"it",
"has",
"expected",
"form",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/fields.py#L280-L292 | train | 24,141 |
swistakm/graceful | src/graceful/serializers.py | MetaSerializer._get_fields | def _get_fields(mcs, bases, namespace):
"""Create fields dictionary to be used in resource class namespace.
Pop all field objects from attributes dict (namespace) and store them
under _field_storage_key atrribute. Also collect all fields from base
classes in order that ensures fields can be overriden.
Args:
bases: all base classes of created serializer class
namespace (dict): namespace as dictionary of attributes
"""
fields = [
(name, namespace.pop(name))
for name, attribute
in list(namespace.items())
if isinstance(attribute, BaseField)
]
for base in reversed(bases):
if hasattr(base, mcs._fields_storage_key):
fields = list(
getattr(base, mcs._fields_storage_key).items()
) + fields
return OrderedDict(fields) | python | def _get_fields(mcs, bases, namespace):
"""Create fields dictionary to be used in resource class namespace.
Pop all field objects from attributes dict (namespace) and store them
under _field_storage_key atrribute. Also collect all fields from base
classes in order that ensures fields can be overriden.
Args:
bases: all base classes of created serializer class
namespace (dict): namespace as dictionary of attributes
"""
fields = [
(name, namespace.pop(name))
for name, attribute
in list(namespace.items())
if isinstance(attribute, BaseField)
]
for base in reversed(bases):
if hasattr(base, mcs._fields_storage_key):
fields = list(
getattr(base, mcs._fields_storage_key).items()
) + fields
return OrderedDict(fields) | [
"def",
"_get_fields",
"(",
"mcs",
",",
"bases",
",",
"namespace",
")",
":",
"fields",
"=",
"[",
"(",
"name",
",",
"namespace",
".",
"pop",
"(",
"name",
")",
")",
"for",
"name",
",",
"attribute",
"in",
"list",
"(",
"namespace",
".",
"items",
"(",
")... | Create fields dictionary to be used in resource class namespace.
Pop all field objects from attributes dict (namespace) and store them
under _field_storage_key atrribute. Also collect all fields from base
classes in order that ensures fields can be overriden.
Args:
bases: all base classes of created serializer class
namespace (dict): namespace as dictionary of attributes | [
"Create",
"fields",
"dictionary",
"to",
"be",
"used",
"in",
"resource",
"class",
"namespace",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L41-L66 | train | 24,142 |
swistakm/graceful | src/graceful/serializers.py | BaseSerializer.to_representation | def to_representation(self, obj):
"""Convert given internal object instance into representation dict.
Representation dict may be later serialized to the content-type
of choice in the resource HTTP method handler.
This loops over all fields and retrieves source keys/attributes as
field values with respect to optional field sources and converts each
one using ``field.to_representation()`` method.
Args:
obj (object): internal object that needs to be represented
Returns:
dict: representation dictionary
"""
representation = {}
for name, field in self.fields.items():
if field.write_only:
continue
# note fields do not know their names in source representation
# but may know what attribute they target from source object
attribute = self.get_attribute(obj, field.source or name)
if attribute is None:
# Skip none attributes so fields do not have to deal with them
representation[name] = [] if field.many else None
elif field.many:
representation[name] = [
field.to_representation(item) for item in attribute
]
else:
representation[name] = field.to_representation(attribute)
return representation | python | def to_representation(self, obj):
"""Convert given internal object instance into representation dict.
Representation dict may be later serialized to the content-type
of choice in the resource HTTP method handler.
This loops over all fields and retrieves source keys/attributes as
field values with respect to optional field sources and converts each
one using ``field.to_representation()`` method.
Args:
obj (object): internal object that needs to be represented
Returns:
dict: representation dictionary
"""
representation = {}
for name, field in self.fields.items():
if field.write_only:
continue
# note fields do not know their names in source representation
# but may know what attribute they target from source object
attribute = self.get_attribute(obj, field.source or name)
if attribute is None:
# Skip none attributes so fields do not have to deal with them
representation[name] = [] if field.many else None
elif field.many:
representation[name] = [
field.to_representation(item) for item in attribute
]
else:
representation[name] = field.to_representation(attribute)
return representation | [
"def",
"to_representation",
"(",
"self",
",",
"obj",
")",
":",
"representation",
"=",
"{",
"}",
"for",
"name",
",",
"field",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"if",
"field",
".",
"write_only",
":",
"continue",
"# note fields do no... | Convert given internal object instance into representation dict.
Representation dict may be later serialized to the content-type
of choice in the resource HTTP method handler.
This loops over all fields and retrieves source keys/attributes as
field values with respect to optional field sources and converts each
one using ``field.to_representation()`` method.
Args:
obj (object): internal object that needs to be represented
Returns:
dict: representation dictionary | [
"Convert",
"given",
"internal",
"object",
"instance",
"into",
"representation",
"dict",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L101-L138 | train | 24,143 |
swistakm/graceful | src/graceful/serializers.py | BaseSerializer.from_representation | def from_representation(self, representation):
"""Convert given representation dict into internal object.
Internal object is simply a dictionary of values with respect to field
sources.
This does not check if all required fields exist or values are
valid in terms of value validation
(see: :meth:`BaseField.validate()`) but still requires all of passed
representation values to be well formed representation (success call
to ``field.from_representation``).
In case of malformed representation it will run additional validation
only to provide a full detailed exception about all that might be
wrong with provided representation.
Args:
representation (dict): dictionary with field representation values
Raises:
DeserializationError: when at least one representation field
is not formed as expected by field object. Information
about additional forbidden/missing/invalid fields is provided
as well.
"""
object_dict = {}
failed = {}
for name, field in self.fields.items():
if name not in representation:
continue
try:
if (
# note: we cannot check for any sequence or iterable
# because of strings and nested dicts.
not isinstance(representation[name], (list, tuple)) and
field.many
):
raise ValueError("field should be sequence")
source = _source(name, field)
value = representation[name]
if field.many:
if not field.allow_null:
object_dict[source] = [
field.from_representation(single_value)
for single_value in value
]
else:
object_dict[source] = [
field.from_representation(single_value)
if single_value is not None else None
for single_value in value
]
else:
if not field.allow_null:
object_dict[source] = field.from_representation(value)
else:
object_dict[source] = field.from_representation(
value) if value else None
except ValueError as err:
failed[name] = str(err)
if failed:
# if failed to parse we eagerly perform validation so full
# information about what is wrong will be returned
try:
self.validate(object_dict)
# note: this exception can be reached with partial==True
# since do not support partial updates yet this has 'no cover'
raise DeserializationError() # pragma: no cover
except DeserializationError as err:
err.failed = failed
raise
return object_dict | python | def from_representation(self, representation):
"""Convert given representation dict into internal object.
Internal object is simply a dictionary of values with respect to field
sources.
This does not check if all required fields exist or values are
valid in terms of value validation
(see: :meth:`BaseField.validate()`) but still requires all of passed
representation values to be well formed representation (success call
to ``field.from_representation``).
In case of malformed representation it will run additional validation
only to provide a full detailed exception about all that might be
wrong with provided representation.
Args:
representation (dict): dictionary with field representation values
Raises:
DeserializationError: when at least one representation field
is not formed as expected by field object. Information
about additional forbidden/missing/invalid fields is provided
as well.
"""
object_dict = {}
failed = {}
for name, field in self.fields.items():
if name not in representation:
continue
try:
if (
# note: we cannot check for any sequence or iterable
# because of strings and nested dicts.
not isinstance(representation[name], (list, tuple)) and
field.many
):
raise ValueError("field should be sequence")
source = _source(name, field)
value = representation[name]
if field.many:
if not field.allow_null:
object_dict[source] = [
field.from_representation(single_value)
for single_value in value
]
else:
object_dict[source] = [
field.from_representation(single_value)
if single_value is not None else None
for single_value in value
]
else:
if not field.allow_null:
object_dict[source] = field.from_representation(value)
else:
object_dict[source] = field.from_representation(
value) if value else None
except ValueError as err:
failed[name] = str(err)
if failed:
# if failed to parse we eagerly perform validation so full
# information about what is wrong will be returned
try:
self.validate(object_dict)
# note: this exception can be reached with partial==True
# since do not support partial updates yet this has 'no cover'
raise DeserializationError() # pragma: no cover
except DeserializationError as err:
err.failed = failed
raise
return object_dict | [
"def",
"from_representation",
"(",
"self",
",",
"representation",
")",
":",
"object_dict",
"=",
"{",
"}",
"failed",
"=",
"{",
"}",
"for",
"name",
",",
"field",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"if",
"name",
"not",
"in",
"repr... | Convert given representation dict into internal object.
Internal object is simply a dictionary of values with respect to field
sources.
This does not check if all required fields exist or values are
valid in terms of value validation
(see: :meth:`BaseField.validate()`) but still requires all of passed
representation values to be well formed representation (success call
to ``field.from_representation``).
In case of malformed representation it will run additional validation
only to provide a full detailed exception about all that might be
wrong with provided representation.
Args:
representation (dict): dictionary with field representation values
Raises:
DeserializationError: when at least one representation field
is not formed as expected by field object. Information
about additional forbidden/missing/invalid fields is provided
as well. | [
"Convert",
"given",
"representation",
"dict",
"into",
"internal",
"object",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L140-L218 | train | 24,144 |
swistakm/graceful | src/graceful/serializers.py | BaseSerializer.get_attribute | def get_attribute(self, obj, attr):
"""Get attribute of given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also object's key from if is a dict or any other kind of mapping.
Note: it will return None if attribute key does not exist
Args:
obj (object): internal object to retrieve data from
Returns:
internal object's key value or attribute
"""
# '*' is a special wildcard character that means whole object
# is passed
if attr == '*':
return obj
# if this is any mapping then instead of attributes use keys
if isinstance(obj, Mapping):
return obj.get(attr, None)
return getattr(obj, attr, None) | python | def get_attribute(self, obj, attr):
"""Get attribute of given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also object's key from if is a dict or any other kind of mapping.
Note: it will return None if attribute key does not exist
Args:
obj (object): internal object to retrieve data from
Returns:
internal object's key value or attribute
"""
# '*' is a special wildcard character that means whole object
# is passed
if attr == '*':
return obj
# if this is any mapping then instead of attributes use keys
if isinstance(obj, Mapping):
return obj.get(attr, None)
return getattr(obj, attr, None) | [
"def",
"get_attribute",
"(",
"self",
",",
"obj",
",",
"attr",
")",
":",
"# '*' is a special wildcard character that means whole object",
"# is passed",
"if",
"attr",
"==",
"'*'",
":",
"return",
"obj",
"# if this is any mapping then instead of attributes use keys",
"if",
"is... | Get attribute of given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also object's key from if is a dict or any other kind of mapping.
Note: it will return None if attribute key does not exist
Args:
obj (object): internal object to retrieve data from
Returns:
internal object's key value or attribute | [
"Get",
"attribute",
"of",
"given",
"object",
"instance",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L299-L323 | train | 24,145 |
swistakm/graceful | src/graceful/serializers.py | BaseSerializer.set_attribute | def set_attribute(self, obj, attr, value):
"""Set value of attribute in given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also a object's key if it is a dict or any other kind of mapping.
Args:
obj (object): object instance to modify
attr (str): attribute (or key) to change
value: value to set
"""
# if this is any mutable mapping then instead of attributes use keys
if isinstance(obj, MutableMapping):
obj[attr] = value
else:
setattr(obj, attr, value) | python | def set_attribute(self, obj, attr, value):
"""Set value of attribute in given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also a object's key if it is a dict or any other kind of mapping.
Args:
obj (object): object instance to modify
attr (str): attribute (or key) to change
value: value to set
"""
# if this is any mutable mapping then instead of attributes use keys
if isinstance(obj, MutableMapping):
obj[attr] = value
else:
setattr(obj, attr, value) | [
"def",
"set_attribute",
"(",
"self",
",",
"obj",
",",
"attr",
",",
"value",
")",
":",
"# if this is any mutable mapping then instead of attributes use keys",
"if",
"isinstance",
"(",
"obj",
",",
"MutableMapping",
")",
":",
"obj",
"[",
"attr",
"]",
"=",
"value",
... | Set value of attribute in given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also a object's key if it is a dict or any other kind of mapping.
Args:
obj (object): object instance to modify
attr (str): attribute (or key) to change
value: value to set | [
"Set",
"value",
"of",
"attribute",
"in",
"given",
"object",
"instance",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L325-L341 | train | 24,146 |
swistakm/graceful | src/graceful/serializers.py | BaseSerializer.describe | def describe(self):
"""Describe all serialized fields.
It returns dictionary of all fields description defined for this
serializer using their own ``describe()`` methods with respect to order
in which they are defined as class attributes.
Returns:
OrderedDict: serializer description
"""
return OrderedDict([
(name, field.describe())
for name, field in self.fields.items()
]) | python | def describe(self):
"""Describe all serialized fields.
It returns dictionary of all fields description defined for this
serializer using their own ``describe()`` methods with respect to order
in which they are defined as class attributes.
Returns:
OrderedDict: serializer description
"""
return OrderedDict([
(name, field.describe())
for name, field in self.fields.items()
]) | [
"def",
"describe",
"(",
"self",
")",
":",
"return",
"OrderedDict",
"(",
"[",
"(",
"name",
",",
"field",
".",
"describe",
"(",
")",
")",
"for",
"name",
",",
"field",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
"]",
")"
] | Describe all serialized fields.
It returns dictionary of all fields description defined for this
serializer using their own ``describe()`` methods with respect to order
in which they are defined as class attributes.
Returns:
OrderedDict: serializer description | [
"Describe",
"all",
"serialized",
"fields",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L343-L357 | train | 24,147 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/config/incluster_config.py | _join_host_port | def _join_host_port(host, port):
"""Adapted golang's net.JoinHostPort"""
template = "%s:%s"
host_requires_bracketing = ':' in host or '%' in host
if host_requires_bracketing:
template = "[%s]:%s"
return template % (host, port) | python | def _join_host_port(host, port):
"""Adapted golang's net.JoinHostPort"""
template = "%s:%s"
host_requires_bracketing = ':' in host or '%' in host
if host_requires_bracketing:
template = "[%s]:%s"
return template % (host, port) | [
"def",
"_join_host_port",
"(",
"host",
",",
"port",
")",
":",
"template",
"=",
"\"%s:%s\"",
"host_requires_bracketing",
"=",
"':'",
"in",
"host",
"or",
"'%'",
"in",
"host",
"if",
"host_requires_bracketing",
":",
"template",
"=",
"\"[%s]:%s\"",
"return",
"templat... | Adapted golang's net.JoinHostPort | [
"Adapted",
"golang",
"s",
"net",
".",
"JoinHostPort"
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/config/incluster_config.py#L27-L33 | train | 24,148 |
swistakm/graceful | src/graceful/resources/mixins.py | BaseMixin.handle | def handle(self, handler, req, resp, **kwargs):
"""Handle given resource manipulation flow in consistent manner.
This mixin is intended to be used only as a base class in new flow
mixin classes. It ensures that regardless of resource manunipulation
semantics (retrieve, get, delete etc.) the flow is always the same:
1. Decode and validate all request parameters from the query string
using ``self.require_params()`` method.
2. Use ``self.require_meta_and_content()`` method to construct ``meta``
and ``content`` dictionaries that will be later used to create
serialized response body.
3. Construct serialized response body using ``self.body()`` method.
Args:
handler (method): resource manipulation method handler.
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified.
**kwargs: additional keyword arguments retrieved from url
template.
Returns:
Content dictionary (preferably resource representation).
"""
params = self.require_params(req)
# future: remove in 1.x
if getattr(self, '_with_context', False):
handler = partial(handler, context=req.context)
meta, content = self.require_meta_and_content(
handler, params, **kwargs
)
self.make_body(resp, params, meta, content)
return content | python | def handle(self, handler, req, resp, **kwargs):
"""Handle given resource manipulation flow in consistent manner.
This mixin is intended to be used only as a base class in new flow
mixin classes. It ensures that regardless of resource manunipulation
semantics (retrieve, get, delete etc.) the flow is always the same:
1. Decode and validate all request parameters from the query string
using ``self.require_params()`` method.
2. Use ``self.require_meta_and_content()`` method to construct ``meta``
and ``content`` dictionaries that will be later used to create
serialized response body.
3. Construct serialized response body using ``self.body()`` method.
Args:
handler (method): resource manipulation method handler.
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified.
**kwargs: additional keyword arguments retrieved from url
template.
Returns:
Content dictionary (preferably resource representation).
"""
params = self.require_params(req)
# future: remove in 1.x
if getattr(self, '_with_context', False):
handler = partial(handler, context=req.context)
meta, content = self.require_meta_and_content(
handler, params, **kwargs
)
self.make_body(resp, params, meta, content)
return content | [
"def",
"handle",
"(",
"self",
",",
"handler",
",",
"req",
",",
"resp",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"self",
".",
"require_params",
"(",
"req",
")",
"# future: remove in 1.x",
"if",
"getattr",
"(",
"self",
",",
"'_with_context'",
",",... | Handle given resource manipulation flow in consistent manner.
This mixin is intended to be used only as a base class in new flow
mixin classes. It ensures that regardless of resource manunipulation
semantics (retrieve, get, delete etc.) the flow is always the same:
1. Decode and validate all request parameters from the query string
using ``self.require_params()`` method.
2. Use ``self.require_meta_and_content()`` method to construct ``meta``
and ``content`` dictionaries that will be later used to create
serialized response body.
3. Construct serialized response body using ``self.body()`` method.
Args:
handler (method): resource manipulation method handler.
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified.
**kwargs: additional keyword arguments retrieved from url
template.
Returns:
Content dictionary (preferably resource representation). | [
"Handle",
"given",
"resource",
"manipulation",
"flow",
"in",
"consistent",
"manner",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L11-L45 | train | 24,149 |
swistakm/graceful | src/graceful/resources/mixins.py | RetrieveMixin.on_get | def on_get(self, req, resp, handler=None, **kwargs):
"""Respond on GET HTTP request assuming resource retrieval flow.
This request handler assumes that GET requests are associated with
single resource instance retrieval. Thus default flow for such requests
is:
* Retrieve single resource instance of prepare its representation by
calling retrieve method handler.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): list method handler to be called. Defaults
to ``self.list``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.retrieve, req, resp, **kwargs
) | python | def on_get(self, req, resp, handler=None, **kwargs):
"""Respond on GET HTTP request assuming resource retrieval flow.
This request handler assumes that GET requests are associated with
single resource instance retrieval. Thus default flow for such requests
is:
* Retrieve single resource instance of prepare its representation by
calling retrieve method handler.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): list method handler to be called. Defaults
to ``self.list``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.retrieve, req, resp, **kwargs
) | [
"def",
"on_get",
"(",
"self",
",",
"req",
",",
"resp",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"handle",
"(",
"handler",
"or",
"self",
".",
"retrieve",
",",
"req",
",",
"resp",
",",
"*",
"*",
"kwargs",
")"
] | Respond on GET HTTP request assuming resource retrieval flow.
This request handler assumes that GET requests are associated with
single resource instance retrieval. Thus default flow for such requests
is:
* Retrieve single resource instance of prepare its representation by
calling retrieve method handler.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): list method handler to be called. Defaults
to ``self.list``.
**kwargs: additional keyword arguments retrieved from url template. | [
"Respond",
"on",
"GET",
"HTTP",
"request",
"assuming",
"resource",
"retrieval",
"flow",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L75-L94 | train | 24,150 |
swistakm/graceful | src/graceful/resources/mixins.py | ListMixin.on_get | def on_get(self, req, resp, handler=None, **kwargs):
"""Respond on GET HTTP request assuming resource list retrieval flow.
This request handler assumes that GET requests are associated with
resource list retrieval. Thus default flow for such requests is:
* Retrieve list of existing resource instances and prepare their
representations by calling list retrieval method handler.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): list method handler to be called. Defaults
to ``self.list``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.list, req, resp, **kwargs
) | python | def on_get(self, req, resp, handler=None, **kwargs):
"""Respond on GET HTTP request assuming resource list retrieval flow.
This request handler assumes that GET requests are associated with
resource list retrieval. Thus default flow for such requests is:
* Retrieve list of existing resource instances and prepare their
representations by calling list retrieval method handler.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): list method handler to be called. Defaults
to ``self.list``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.list, req, resp, **kwargs
) | [
"def",
"on_get",
"(",
"self",
",",
"req",
",",
"resp",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"handle",
"(",
"handler",
"or",
"self",
".",
"list",
",",
"req",
",",
"resp",
",",
"*",
"*",
"kwargs",
")"
] | Respond on GET HTTP request assuming resource list retrieval flow.
This request handler assumes that GET requests are associated with
resource list retrieval. Thus default flow for such requests is:
* Retrieve list of existing resource instances and prepare their
representations by calling list retrieval method handler.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): list method handler to be called. Defaults
to ``self.list``.
**kwargs: additional keyword arguments retrieved from url template. | [
"Respond",
"on",
"GET",
"HTTP",
"request",
"assuming",
"resource",
"list",
"retrieval",
"flow",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L124-L142 | train | 24,151 |
swistakm/graceful | src/graceful/resources/mixins.py | DeleteMixin.on_delete | def on_delete(self, req, resp, handler=None, **kwargs):
"""Respond on DELETE HTTP request assuming resource deletion flow.
This request handler assumes that DELETE requests are associated with
resource deletion. Thus default flow for such requests is:
* Delete existing resource instance.
* Set response status code to ``202 Accepted``.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): deletion method handler to be called. Defaults
to ``self.delete``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.delete, req, resp, **kwargs
)
resp.status = falcon.HTTP_ACCEPTED | python | def on_delete(self, req, resp, handler=None, **kwargs):
"""Respond on DELETE HTTP request assuming resource deletion flow.
This request handler assumes that DELETE requests are associated with
resource deletion. Thus default flow for such requests is:
* Delete existing resource instance.
* Set response status code to ``202 Accepted``.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): deletion method handler to be called. Defaults
to ``self.delete``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.delete, req, resp, **kwargs
)
resp.status = falcon.HTTP_ACCEPTED | [
"def",
"on_delete",
"(",
"self",
",",
"req",
",",
"resp",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"handle",
"(",
"handler",
"or",
"self",
".",
"delete",
",",
"req",
",",
"resp",
",",
"*",
"*",
"kwargs",
")",
... | Respond on DELETE HTTP request assuming resource deletion flow.
This request handler assumes that DELETE requests are associated with
resource deletion. Thus default flow for such requests is:
* Delete existing resource instance.
* Set response status code to ``202 Accepted``.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): deletion method handler to be called. Defaults
to ``self.delete``.
**kwargs: additional keyword arguments retrieved from url template. | [
"Respond",
"on",
"DELETE",
"HTTP",
"request",
"assuming",
"resource",
"deletion",
"flow",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L168-L188 | train | 24,152 |
swistakm/graceful | src/graceful/resources/mixins.py | UpdateMixin.on_put | def on_put(self, req, resp, handler=None, **kwargs):
"""Respond on PUT HTTP request assuming resource update flow.
This request handler assumes that PUT requests are associated with
resource update/modification. Thus default flow for such requests is:
* Modify existing resource instance and prepare its representation by
calling its update method handler.
* Set response status code to ``202 Accepted``.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): update method handler to be called. Defaults
to ``self.update``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.update, req, resp, **kwargs
)
resp.status = falcon.HTTP_ACCEPTED | python | def on_put(self, req, resp, handler=None, **kwargs):
"""Respond on PUT HTTP request assuming resource update flow.
This request handler assumes that PUT requests are associated with
resource update/modification. Thus default flow for such requests is:
* Modify existing resource instance and prepare its representation by
calling its update method handler.
* Set response status code to ``202 Accepted``.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): update method handler to be called. Defaults
to ``self.update``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.update, req, resp, **kwargs
)
resp.status = falcon.HTTP_ACCEPTED | [
"def",
"on_put",
"(",
"self",
",",
"req",
",",
"resp",
",",
"handler",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"handle",
"(",
"handler",
"or",
"self",
".",
"update",
",",
"req",
",",
"resp",
",",
"*",
"*",
"kwargs",
")",
"r... | Respond on PUT HTTP request assuming resource update flow.
This request handler assumes that PUT requests are associated with
resource update/modification. Thus default flow for such requests is:
* Modify existing resource instance and prepare its representation by
calling its update method handler.
* Set response status code to ``202 Accepted``.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): update method handler to be called. Defaults
to ``self.update``.
**kwargs: additional keyword arguments retrieved from url template. | [
"Respond",
"on",
"PUT",
"HTTP",
"request",
"assuming",
"resource",
"update",
"flow",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L217-L237 | train | 24,153 |
swistakm/graceful | src/graceful/resources/mixins.py | PaginatedMixin.add_pagination_meta | def add_pagination_meta(self, params, meta):
"""Extend default meta dictionary value with pagination hints.
Note:
This method handler attaches values to ``meta`` dictionary without
changing it's reference. This means that you should never replace
``meta`` dictionary with any other dict instance but simply modify
its content.
Args:
params (dict): dictionary of decoded parameter values
meta (dict): dictionary of meta values attached to response
"""
meta['page_size'] = params['page_size']
meta['page'] = params['page']
meta['prev'] = "page={0}&page_size={1}".format(
params['page'] - 1, params['page_size']
) if meta['page'] > 0 else None
meta['next'] = "page={0}&page_size={1}".format(
params['page'] + 1, params['page_size']
) if meta.get('has_more', True) else None | python | def add_pagination_meta(self, params, meta):
"""Extend default meta dictionary value with pagination hints.
Note:
This method handler attaches values to ``meta`` dictionary without
changing it's reference. This means that you should never replace
``meta`` dictionary with any other dict instance but simply modify
its content.
Args:
params (dict): dictionary of decoded parameter values
meta (dict): dictionary of meta values attached to response
"""
meta['page_size'] = params['page_size']
meta['page'] = params['page']
meta['prev'] = "page={0}&page_size={1}".format(
params['page'] - 1, params['page_size']
) if meta['page'] > 0 else None
meta['next'] = "page={0}&page_size={1}".format(
params['page'] + 1, params['page_size']
) if meta.get('has_more', True) else None | [
"def",
"add_pagination_meta",
"(",
"self",
",",
"params",
",",
"meta",
")",
":",
"meta",
"[",
"'page_size'",
"]",
"=",
"params",
"[",
"'page_size'",
"]",
"meta",
"[",
"'page'",
"]",
"=",
"params",
"[",
"'page'",
"]",
"meta",
"[",
"'prev'",
"]",
"=",
... | Extend default meta dictionary value with pagination hints.
Note:
This method handler attaches values to ``meta`` dictionary without
changing it's reference. This means that you should never replace
``meta`` dictionary with any other dict instance but simply modify
its content.
Args:
params (dict): dictionary of decoded parameter values
meta (dict): dictionary of meta values attached to response | [
"Extend",
"default",
"meta",
"dictionary",
"value",
"with",
"pagination",
"hints",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L396-L418 | train | 24,154 |
swistakm/graceful | src/graceful/resources/base.py | MetaResource._get_params | def _get_params(mcs, bases, namespace):
"""Create params dictionary to be used in resource class namespace.
Pop all parameter objects from attributes dict (namespace)
and store them under _params_storage_key atrribute.
Also collect all params from base classes in order that ensures
params can be overriden.
Args:
bases: all base classes of created resource class
namespace (dict): namespace as dictionary of attributes
"""
params = [
(name, namespace.pop(name))
for name, attribute
in list(namespace.items())
if isinstance(attribute, BaseParam)
]
for base in reversed(bases):
if hasattr(base, mcs._params_storage_key):
params = list(
getattr(base, mcs._params_storage_key).items()
) + params
return OrderedDict(params) | python | def _get_params(mcs, bases, namespace):
"""Create params dictionary to be used in resource class namespace.
Pop all parameter objects from attributes dict (namespace)
and store them under _params_storage_key atrribute.
Also collect all params from base classes in order that ensures
params can be overriden.
Args:
bases: all base classes of created resource class
namespace (dict): namespace as dictionary of attributes
"""
params = [
(name, namespace.pop(name))
for name, attribute
in list(namespace.items())
if isinstance(attribute, BaseParam)
]
for base in reversed(bases):
if hasattr(base, mcs._params_storage_key):
params = list(
getattr(base, mcs._params_storage_key).items()
) + params
return OrderedDict(params) | [
"def",
"_get_params",
"(",
"mcs",
",",
"bases",
",",
"namespace",
")",
":",
"params",
"=",
"[",
"(",
"name",
",",
"namespace",
".",
"pop",
"(",
"name",
")",
")",
"for",
"name",
",",
"attribute",
"in",
"list",
"(",
"namespace",
".",
"items",
"(",
")... | Create params dictionary to be used in resource class namespace.
Pop all parameter objects from attributes dict (namespace)
and store them under _params_storage_key atrribute.
Also collect all params from base classes in order that ensures
params can be overriden.
Args:
bases: all base classes of created resource class
namespace (dict): namespace as dictionary of attributes | [
"Create",
"params",
"dictionary",
"to",
"be",
"used",
"in",
"resource",
"class",
"namespace",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L35-L61 | train | 24,155 |
swistakm/graceful | src/graceful/resources/base.py | BaseResource.make_body | def make_body(self, resp, params, meta, content):
"""Construct response body in ``resp`` object using JSON serialization.
Args:
resp (falcon.Response): response object where to include
serialized body
params (dict): dictionary of parsed parameters
meta (dict): dictionary of metadata to be included in 'meta'
section of response
content (dict): dictionary of response content (resource
representation) to be included in 'content' section of response
Returns:
None
"""
response = {
'meta': meta,
'content': content
}
resp.content_type = 'application/json'
resp.body = json.dumps(
response,
indent=params['indent'] or None if 'indent' in params else None
) | python | def make_body(self, resp, params, meta, content):
"""Construct response body in ``resp`` object using JSON serialization.
Args:
resp (falcon.Response): response object where to include
serialized body
params (dict): dictionary of parsed parameters
meta (dict): dictionary of metadata to be included in 'meta'
section of response
content (dict): dictionary of response content (resource
representation) to be included in 'content' section of response
Returns:
None
"""
response = {
'meta': meta,
'content': content
}
resp.content_type = 'application/json'
resp.body = json.dumps(
response,
indent=params['indent'] or None if 'indent' in params else None
) | [
"def",
"make_body",
"(",
"self",
",",
"resp",
",",
"params",
",",
"meta",
",",
"content",
")",
":",
"response",
"=",
"{",
"'meta'",
":",
"meta",
",",
"'content'",
":",
"content",
"}",
"resp",
".",
"content_type",
"=",
"'application/json'",
"resp",
".",
... | Construct response body in ``resp`` object using JSON serialization.
Args:
resp (falcon.Response): response object where to include
serialized body
params (dict): dictionary of parsed parameters
meta (dict): dictionary of metadata to be included in 'meta'
section of response
content (dict): dictionary of response content (resource
representation) to be included in 'content' section of response
Returns:
None | [
"Construct",
"response",
"body",
"in",
"resp",
"object",
"using",
"JSON",
"serialization",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L153-L177 | train | 24,156 |
swistakm/graceful | src/graceful/resources/base.py | BaseResource.allowed_methods | def allowed_methods(self):
"""Return list of allowed HTTP methods on this resource.
This is only for purpose of making resource description.
Returns:
list: list of allowed HTTP method names (uppercase)
"""
return [
method
for method, allowed in (
('GET', hasattr(self, 'on_get')),
('POST', hasattr(self, 'on_post')),
('PUT', hasattr(self, 'on_put')),
('PATCH', hasattr(self, 'on_patch')),
('DELETE', hasattr(self, 'on_delete')),
('HEAD', hasattr(self, 'on_head')),
('OPTIONS', hasattr(self, 'on_options')),
) if allowed
] | python | def allowed_methods(self):
"""Return list of allowed HTTP methods on this resource.
This is only for purpose of making resource description.
Returns:
list: list of allowed HTTP method names (uppercase)
"""
return [
method
for method, allowed in (
('GET', hasattr(self, 'on_get')),
('POST', hasattr(self, 'on_post')),
('PUT', hasattr(self, 'on_put')),
('PATCH', hasattr(self, 'on_patch')),
('DELETE', hasattr(self, 'on_delete')),
('HEAD', hasattr(self, 'on_head')),
('OPTIONS', hasattr(self, 'on_options')),
) if allowed
] | [
"def",
"allowed_methods",
"(",
"self",
")",
":",
"return",
"[",
"method",
"for",
"method",
",",
"allowed",
"in",
"(",
"(",
"'GET'",
",",
"hasattr",
"(",
"self",
",",
"'on_get'",
")",
")",
",",
"(",
"'POST'",
",",
"hasattr",
"(",
"self",
",",
"'on_pos... | Return list of allowed HTTP methods on this resource.
This is only for purpose of making resource description.
Returns:
list: list of allowed HTTP method names (uppercase) | [
"Return",
"list",
"of",
"allowed",
"HTTP",
"methods",
"on",
"this",
"resource",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L179-L199 | train | 24,157 |
swistakm/graceful | src/graceful/resources/base.py | BaseResource.describe | def describe(self, req=None, resp=None, **kwargs):
"""Describe API resource using resource introspection.
Additional description on derrived resource class can be added using
keyword arguments and calling ``super().decribe()`` method call
like following:
.. code-block:: python
class SomeResource(BaseResource):
def describe(req, resp, **kwargs):
return super().describe(
req, resp, type='list', **kwargs
)
Args:
req (falcon.Request): request object
resp (falcon.Response): response object
kwargs (dict): dictionary of values created from resource url
template
Returns:
dict: dictionary with resource descritpion information
.. versionchanged:: 0.2.0
The `req` and `resp` parameters became optional to ease the
implementation of application-level documentation generators.
"""
description = {
'params': OrderedDict([
(name, param.describe())
for name, param in self.params.items()
]),
'details':
inspect.cleandoc(
self.__class__.__doc__ or
"This resource does not have description yet"
),
'name': self.__class__.__name__,
'methods': self.allowed_methods()
}
# note: add path to resource description only if request object was
# provided in order to make auto-documentation engines simpler
if req:
description['path'] = req.path
description.update(**kwargs)
return description | python | def describe(self, req=None, resp=None, **kwargs):
"""Describe API resource using resource introspection.
Additional description on derrived resource class can be added using
keyword arguments and calling ``super().decribe()`` method call
like following:
.. code-block:: python
class SomeResource(BaseResource):
def describe(req, resp, **kwargs):
return super().describe(
req, resp, type='list', **kwargs
)
Args:
req (falcon.Request): request object
resp (falcon.Response): response object
kwargs (dict): dictionary of values created from resource url
template
Returns:
dict: dictionary with resource descritpion information
.. versionchanged:: 0.2.0
The `req` and `resp` parameters became optional to ease the
implementation of application-level documentation generators.
"""
description = {
'params': OrderedDict([
(name, param.describe())
for name, param in self.params.items()
]),
'details':
inspect.cleandoc(
self.__class__.__doc__ or
"This resource does not have description yet"
),
'name': self.__class__.__name__,
'methods': self.allowed_methods()
}
# note: add path to resource description only if request object was
# provided in order to make auto-documentation engines simpler
if req:
description['path'] = req.path
description.update(**kwargs)
return description | [
"def",
"describe",
"(",
"self",
",",
"req",
"=",
"None",
",",
"resp",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"description",
"=",
"{",
"'params'",
":",
"OrderedDict",
"(",
"[",
"(",
"name",
",",
"param",
".",
"describe",
"(",
")",
")",
"f... | Describe API resource using resource introspection.
Additional description on derrived resource class can be added using
keyword arguments and calling ``super().decribe()`` method call
like following:
.. code-block:: python
class SomeResource(BaseResource):
def describe(req, resp, **kwargs):
return super().describe(
req, resp, type='list', **kwargs
)
Args:
req (falcon.Request): request object
resp (falcon.Response): response object
kwargs (dict): dictionary of values created from resource url
template
Returns:
dict: dictionary with resource descritpion information
.. versionchanged:: 0.2.0
The `req` and `resp` parameters became optional to ease the
implementation of application-level documentation generators. | [
"Describe",
"API",
"resource",
"using",
"resource",
"introspection",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L201-L248 | train | 24,158 |
swistakm/graceful | src/graceful/resources/base.py | BaseResource.on_options | def on_options(self, req, resp, **kwargs):
"""Respond with JSON formatted resource description on OPTIONS request.
Args:
req (falcon.Request): Optional request object. Defaults to None.
resp (falcon.Response): Optional response object. Defaults to None.
kwargs (dict): Dictionary of values created by falcon from
resource uri template.
Returns:
None
.. versionchanged:: 0.2.0
Default ``OPTIONS`` responses include ``Allow`` header with list of
allowed HTTP methods.
"""
resp.set_header('Allow', ', '.join(self.allowed_methods()))
resp.body = json.dumps(self.describe(req, resp))
resp.content_type = 'application/json' | python | def on_options(self, req, resp, **kwargs):
"""Respond with JSON formatted resource description on OPTIONS request.
Args:
req (falcon.Request): Optional request object. Defaults to None.
resp (falcon.Response): Optional response object. Defaults to None.
kwargs (dict): Dictionary of values created by falcon from
resource uri template.
Returns:
None
.. versionchanged:: 0.2.0
Default ``OPTIONS`` responses include ``Allow`` header with list of
allowed HTTP methods.
"""
resp.set_header('Allow', ', '.join(self.allowed_methods()))
resp.body = json.dumps(self.describe(req, resp))
resp.content_type = 'application/json' | [
"def",
"on_options",
"(",
"self",
",",
"req",
",",
"resp",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
".",
"set_header",
"(",
"'Allow'",
",",
"', '",
".",
"join",
"(",
"self",
".",
"allowed_methods",
"(",
")",
")",
")",
"resp",
".",
"body",
"=",
... | Respond with JSON formatted resource description on OPTIONS request.
Args:
req (falcon.Request): Optional request object. Defaults to None.
resp (falcon.Response): Optional response object. Defaults to None.
kwargs (dict): Dictionary of values created by falcon from
resource uri template.
Returns:
None
.. versionchanged:: 0.2.0
Default ``OPTIONS`` responses include ``Allow`` header with list of
allowed HTTP methods. | [
"Respond",
"with",
"JSON",
"formatted",
"resource",
"description",
"on",
"OPTIONS",
"request",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L250-L269 | train | 24,159 |
swistakm/graceful | src/graceful/resources/base.py | BaseResource.require_params | def require_params(self, req):
"""Require all defined parameters from request query string.
Raises ``falcon.errors.HTTPMissingParam`` exception if any of required
parameters is missing and ``falcon.errors.HTTPInvalidParam`` if any
of parameters could not be understood (wrong format).
Args:
req (falcon.Request): request object
"""
params = {}
for name, param in self.params.items():
if name not in req.params and param.required:
# we could simply raise with this single param or use get_param
# with required=True parameter but for client convenience
# we prefer to list all missing params that are required
missing = set(
p for p in self.params
if self.params[p].required
) - set(req.params.keys())
raise errors.HTTPMissingParam(", ".join(missing))
elif name in req.params or param.default:
# Note: lack of key in req.params means it was not specified
# so unless there is default value it will not be included in
# output params dict.
# This way we have explicit information that param was
# not specified. Using None would not be as good because param
# class can also return None from `.value()` method as a valid
# translated value.
try:
if param.many:
# params with "many" enabled need special care
values = req.get_param_as_list(
# note: falcon allows to pass value handler using
# `transform` param so we do not need to
# iterate through list manually
name, param.validated_value
) or [
param.default and
param.validated_value(param.default)
]
params[name] = param.container(values)
else:
# note that if many==False and query parameter
# occurs multiple times in qs then it is
# **unspecified** which one will be used. See:
# http://falcon.readthedocs.org/en/latest/api/request_and_response.html#falcon.Request.get_param # noqa
params[name] = param.validated_value(
req.get_param(name, default=param.default)
)
except ValidationError as err:
# ValidationError allows to easily translate itself to
# to falcon's HTTPInvalidParam (Bad Request HTTP response)
raise err.as_invalid_param(name)
except ValueError as err:
# Other parsing issues are expected to raise ValueError
raise errors.HTTPInvalidParam(str(err), name)
return params | python | def require_params(self, req):
"""Require all defined parameters from request query string.
Raises ``falcon.errors.HTTPMissingParam`` exception if any of required
parameters is missing and ``falcon.errors.HTTPInvalidParam`` if any
of parameters could not be understood (wrong format).
Args:
req (falcon.Request): request object
"""
params = {}
for name, param in self.params.items():
if name not in req.params and param.required:
# we could simply raise with this single param or use get_param
# with required=True parameter but for client convenience
# we prefer to list all missing params that are required
missing = set(
p for p in self.params
if self.params[p].required
) - set(req.params.keys())
raise errors.HTTPMissingParam(", ".join(missing))
elif name in req.params or param.default:
# Note: lack of key in req.params means it was not specified
# so unless there is default value it will not be included in
# output params dict.
# This way we have explicit information that param was
# not specified. Using None would not be as good because param
# class can also return None from `.value()` method as a valid
# translated value.
try:
if param.many:
# params with "many" enabled need special care
values = req.get_param_as_list(
# note: falcon allows to pass value handler using
# `transform` param so we do not need to
# iterate through list manually
name, param.validated_value
) or [
param.default and
param.validated_value(param.default)
]
params[name] = param.container(values)
else:
# note that if many==False and query parameter
# occurs multiple times in qs then it is
# **unspecified** which one will be used. See:
# http://falcon.readthedocs.org/en/latest/api/request_and_response.html#falcon.Request.get_param # noqa
params[name] = param.validated_value(
req.get_param(name, default=param.default)
)
except ValidationError as err:
# ValidationError allows to easily translate itself to
# to falcon's HTTPInvalidParam (Bad Request HTTP response)
raise err.as_invalid_param(name)
except ValueError as err:
# Other parsing issues are expected to raise ValueError
raise errors.HTTPInvalidParam(str(err), name)
return params | [
"def",
"require_params",
"(",
"self",
",",
"req",
")",
":",
"params",
"=",
"{",
"}",
"for",
"name",
",",
"param",
"in",
"self",
".",
"params",
".",
"items",
"(",
")",
":",
"if",
"name",
"not",
"in",
"req",
".",
"params",
"and",
"param",
".",
"req... | Require all defined parameters from request query string.
Raises ``falcon.errors.HTTPMissingParam`` exception if any of required
parameters is missing and ``falcon.errors.HTTPInvalidParam`` if any
of parameters could not be understood (wrong format).
Args:
req (falcon.Request): request object | [
"Require",
"all",
"defined",
"parameters",
"from",
"request",
"query",
"string",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L271-L335 | train | 24,160 |
swistakm/graceful | src/graceful/resources/base.py | BaseResource.require_meta_and_content | def require_meta_and_content(self, content_handler, params, **kwargs):
"""Require 'meta' and 'content' dictionaries using proper hander.
Args:
content_handler (callable): function that accepts
``params, meta, **kwargs`` argument and returns dictionary
for ``content`` response section
params (dict): dictionary of parsed resource parameters
kwargs (dict): dictionary of values created from resource url
template
Returns:
tuple (meta, content): two-tuple with dictionaries of ``meta`` and
``content`` response sections
"""
meta = {
'params': params
}
content = content_handler(params, meta, **kwargs)
meta['params'] = params
return meta, content | python | def require_meta_and_content(self, content_handler, params, **kwargs):
"""Require 'meta' and 'content' dictionaries using proper hander.
Args:
content_handler (callable): function that accepts
``params, meta, **kwargs`` argument and returns dictionary
for ``content`` response section
params (dict): dictionary of parsed resource parameters
kwargs (dict): dictionary of values created from resource url
template
Returns:
tuple (meta, content): two-tuple with dictionaries of ``meta`` and
``content`` response sections
"""
meta = {
'params': params
}
content = content_handler(params, meta, **kwargs)
meta['params'] = params
return meta, content | [
"def",
"require_meta_and_content",
"(",
"self",
",",
"content_handler",
",",
"params",
",",
"*",
"*",
"kwargs",
")",
":",
"meta",
"=",
"{",
"'params'",
":",
"params",
"}",
"content",
"=",
"content_handler",
"(",
"params",
",",
"meta",
",",
"*",
"*",
"kwa... | Require 'meta' and 'content' dictionaries using proper hander.
Args:
content_handler (callable): function that accepts
``params, meta, **kwargs`` argument and returns dictionary
for ``content`` response section
params (dict): dictionary of parsed resource parameters
kwargs (dict): dictionary of values created from resource url
template
Returns:
tuple (meta, content): two-tuple with dictionaries of ``meta`` and
``content`` response sections | [
"Require",
"meta",
"and",
"content",
"dictionaries",
"using",
"proper",
"hander",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L337-L358 | train | 24,161 |
swistakm/graceful | src/graceful/resources/base.py | BaseResource.require_representation | def require_representation(self, req):
"""Require raw representation dictionary from falcon request object.
This does not perform any field parsing or validation but only uses
allowed content-encoding handler to decode content body.
Note:
Currently only JSON is allowed as content type.
Args:
req (falcon.Request): request object
Returns:
dict: raw dictionary of representation supplied in request body
"""
try:
type_, subtype, _ = parse_mime_type(req.content_type)
content_type = '/'.join((type_, subtype))
except:
raise falcon.HTTPUnsupportedMediaType(
description="Invalid Content-Type header: {}".format(
req.content_type
)
)
if content_type == 'application/json':
body = req.stream.read()
return json.loads(body.decode('utf-8'))
else:
raise falcon.HTTPUnsupportedMediaType(
description="only JSON supported, got: {}".format(content_type)
) | python | def require_representation(self, req):
"""Require raw representation dictionary from falcon request object.
This does not perform any field parsing or validation but only uses
allowed content-encoding handler to decode content body.
Note:
Currently only JSON is allowed as content type.
Args:
req (falcon.Request): request object
Returns:
dict: raw dictionary of representation supplied in request body
"""
try:
type_, subtype, _ = parse_mime_type(req.content_type)
content_type = '/'.join((type_, subtype))
except:
raise falcon.HTTPUnsupportedMediaType(
description="Invalid Content-Type header: {}".format(
req.content_type
)
)
if content_type == 'application/json':
body = req.stream.read()
return json.loads(body.decode('utf-8'))
else:
raise falcon.HTTPUnsupportedMediaType(
description="only JSON supported, got: {}".format(content_type)
) | [
"def",
"require_representation",
"(",
"self",
",",
"req",
")",
":",
"try",
":",
"type_",
",",
"subtype",
",",
"_",
"=",
"parse_mime_type",
"(",
"req",
".",
"content_type",
")",
"content_type",
"=",
"'/'",
".",
"join",
"(",
"(",
"type_",
",",
"subtype",
... | Require raw representation dictionary from falcon request object.
This does not perform any field parsing or validation but only uses
allowed content-encoding handler to decode content body.
Note:
Currently only JSON is allowed as content type.
Args:
req (falcon.Request): request object
Returns:
dict: raw dictionary of representation supplied in request body | [
"Require",
"raw",
"representation",
"dictionary",
"from",
"falcon",
"request",
"object",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L360-L392 | train | 24,162 |
swistakm/graceful | src/graceful/resources/base.py | BaseResource.require_validated | def require_validated(self, req, partial=False, bulk=False):
"""Require fully validated internal object dictionary.
Internal object dictionary creation is based on content-decoded
representation retrieved from request body. Internal object validation
is performed using resource serializer.
Args:
req (falcon.Request): request object
partial (bool): set to True if partially complete representation
is accepted (e.g. for patching instead of full update). Missing
fields in representation will be skiped.
bulk (bool): set to True if request payload represents multiple
resources instead of single one.
Returns:
dict: dictionary of fields and values representing internal object.
Each value is a result of ``field.from_representation`` call.
"""
representations = [
self.require_representation(req)
] if not bulk else self.require_representation(req)
if bulk and not isinstance(representations, list):
raise ValidationError(
"Request payload should represent a list of resources."
).as_bad_request()
object_dicts = []
try:
for representation in representations:
object_dict = self.serializer.from_representation(
representation
)
self.serializer.validate(object_dict, partial)
object_dicts.append(object_dict)
except DeserializationError as err:
# when working on Resource we know that we can finally raise
# bad request exceptions
raise err.as_bad_request()
except ValidationError as err:
# ValidationError is a suggested way to validate whole resource
# so we also are prepared to catch it
raise err.as_bad_request()
return object_dicts if bulk else object_dicts[0] | python | def require_validated(self, req, partial=False, bulk=False):
"""Require fully validated internal object dictionary.
Internal object dictionary creation is based on content-decoded
representation retrieved from request body. Internal object validation
is performed using resource serializer.
Args:
req (falcon.Request): request object
partial (bool): set to True if partially complete representation
is accepted (e.g. for patching instead of full update). Missing
fields in representation will be skiped.
bulk (bool): set to True if request payload represents multiple
resources instead of single one.
Returns:
dict: dictionary of fields and values representing internal object.
Each value is a result of ``field.from_representation`` call.
"""
representations = [
self.require_representation(req)
] if not bulk else self.require_representation(req)
if bulk and not isinstance(representations, list):
raise ValidationError(
"Request payload should represent a list of resources."
).as_bad_request()
object_dicts = []
try:
for representation in representations:
object_dict = self.serializer.from_representation(
representation
)
self.serializer.validate(object_dict, partial)
object_dicts.append(object_dict)
except DeserializationError as err:
# when working on Resource we know that we can finally raise
# bad request exceptions
raise err.as_bad_request()
except ValidationError as err:
# ValidationError is a suggested way to validate whole resource
# so we also are prepared to catch it
raise err.as_bad_request()
return object_dicts if bulk else object_dicts[0] | [
"def",
"require_validated",
"(",
"self",
",",
"req",
",",
"partial",
"=",
"False",
",",
"bulk",
"=",
"False",
")",
":",
"representations",
"=",
"[",
"self",
".",
"require_representation",
"(",
"req",
")",
"]",
"if",
"not",
"bulk",
"else",
"self",
".",
... | Require fully validated internal object dictionary.
Internal object dictionary creation is based on content-decoded
representation retrieved from request body. Internal object validation
is performed using resource serializer.
Args:
req (falcon.Request): request object
partial (bool): set to True if partially complete representation
is accepted (e.g. for patching instead of full update). Missing
fields in representation will be skiped.
bulk (bool): set to True if request payload represents multiple
resources instead of single one.
Returns:
dict: dictionary of fields and values representing internal object.
Each value is a result of ``field.from_representation`` call. | [
"Require",
"fully",
"validated",
"internal",
"object",
"dictionary",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L394-L443 | train | 24,163 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/models/admissionregistration_v1beta1_webhook_client_config.py | AdmissionregistrationV1beta1WebhookClientConfig.ca_bundle | def ca_bundle(self, ca_bundle):
"""Sets the ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig.
`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. # noqa: E501
:param ca_bundle: The ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig. # noqa: E501
:type: str
"""
if ca_bundle is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', ca_bundle): # noqa: E501
raise ValueError(r"Invalid value for `ca_bundle`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501
self._ca_bundle = ca_bundle | python | def ca_bundle(self, ca_bundle):
"""Sets the ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig.
`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. # noqa: E501
:param ca_bundle: The ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig. # noqa: E501
:type: str
"""
if ca_bundle is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', ca_bundle): # noqa: E501
raise ValueError(r"Invalid value for `ca_bundle`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501
self._ca_bundle = ca_bundle | [
"def",
"ca_bundle",
"(",
"self",
",",
"ca_bundle",
")",
":",
"if",
"ca_bundle",
"is",
"not",
"None",
"and",
"not",
"re",
".",
"search",
"(",
"r'^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$'",
",",
"ca_bundle",
")",
":",
"# noqa: E501",
"rai... | Sets the ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig.
`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. # noqa: E501
:param ca_bundle: The ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig. # noqa: E501
:type: str | [
"Sets",
"the",
"ca_bundle",
"of",
"this",
"AdmissionregistrationV1beta1WebhookClientConfig",
"."
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/models/admissionregistration_v1beta1_webhook_client_config.py#L72-L83 | train | 24,164 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/models/v1beta1_certificate_signing_request_status.py | V1beta1CertificateSigningRequestStatus.certificate | def certificate(self, certificate):
"""Sets the certificate of this V1beta1CertificateSigningRequestStatus.
If request was approved, the controller will place the issued certificate here. # noqa: E501
:param certificate: The certificate of this V1beta1CertificateSigningRequestStatus. # noqa: E501
:type: str
"""
if certificate is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', certificate): # noqa: E501
raise ValueError(r"Invalid value for `certificate`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501
self._certificate = certificate | python | def certificate(self, certificate):
"""Sets the certificate of this V1beta1CertificateSigningRequestStatus.
If request was approved, the controller will place the issued certificate here. # noqa: E501
:param certificate: The certificate of this V1beta1CertificateSigningRequestStatus. # noqa: E501
:type: str
"""
if certificate is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', certificate): # noqa: E501
raise ValueError(r"Invalid value for `certificate`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501
self._certificate = certificate | [
"def",
"certificate",
"(",
"self",
",",
"certificate",
")",
":",
"if",
"certificate",
"is",
"not",
"None",
"and",
"not",
"re",
".",
"search",
"(",
"r'^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$'",
",",
"certificate",
")",
":",
"# noqa: E501"... | Sets the certificate of this V1beta1CertificateSigningRequestStatus.
If request was approved, the controller will place the issued certificate here. # noqa: E501
:param certificate: The certificate of this V1beta1CertificateSigningRequestStatus. # noqa: E501
:type: str | [
"Sets",
"the",
"certificate",
"of",
"this",
"V1beta1CertificateSigningRequestStatus",
"."
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/models/v1beta1_certificate_signing_request_status.py#L67-L78 | train | 24,165 |
swistakm/graceful | src/graceful/resources/generic.py | ListAPI.describe | def describe(self, req=None, resp=None, **kwargs):
"""Extend default endpoint description with serializer description."""
return super().describe(
req, resp,
type='list',
fields=self.serializer.describe() if self.serializer else None,
**kwargs
) | python | def describe(self, req=None, resp=None, **kwargs):
"""Extend default endpoint description with serializer description."""
return super().describe(
req, resp,
type='list',
fields=self.serializer.describe() if self.serializer else None,
**kwargs
) | [
"def",
"describe",
"(",
"self",
",",
"req",
"=",
"None",
",",
"resp",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
")",
".",
"describe",
"(",
"req",
",",
"resp",
",",
"type",
"=",
"'list'",
",",
"fields",
"=",
"self",
... | Extend default endpoint description with serializer description. | [
"Extend",
"default",
"endpoint",
"description",
"with",
"serializer",
"description",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/generic.py#L163-L170 | train | 24,166 |
swistakm/graceful | src/graceful/authentication.py | DummyUserStorage.get_user | def get_user(
self, identified_with, identifier, req, resp, resource, uri_kwargs
):
"""Return default user object."""
return self.user | python | def get_user(
self, identified_with, identifier, req, resp, resource, uri_kwargs
):
"""Return default user object."""
return self.user | [
"def",
"get_user",
"(",
"self",
",",
"identified_with",
",",
"identifier",
",",
"req",
",",
"resp",
",",
"resource",
",",
"uri_kwargs",
")",
":",
"return",
"self",
".",
"user"
] | Return default user object. | [
"Return",
"default",
"user",
"object",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L77-L81 | train | 24,167 |
swistakm/graceful | src/graceful/authentication.py | KeyValueUserStorage._get_storage_key | def _get_storage_key(self, identified_with, identifier):
"""Get key string for given user identifier in consistent manner."""
return ':'.join((
self.key_prefix, identified_with.name,
self.hash_identifier(identified_with, identifier),
)) | python | def _get_storage_key(self, identified_with, identifier):
"""Get key string for given user identifier in consistent manner."""
return ':'.join((
self.key_prefix, identified_with.name,
self.hash_identifier(identified_with, identifier),
)) | [
"def",
"_get_storage_key",
"(",
"self",
",",
"identified_with",
",",
"identifier",
")",
":",
"return",
"':'",
".",
"join",
"(",
"(",
"self",
".",
"key_prefix",
",",
"identified_with",
".",
"name",
",",
"self",
".",
"hash_identifier",
"(",
"identified_with",
... | Get key string for given user identifier in consistent manner. | [
"Get",
"key",
"string",
"for",
"given",
"user",
"identifier",
"in",
"consistent",
"manner",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L166-L171 | train | 24,168 |
swistakm/graceful | src/graceful/authentication.py | KeyValueUserStorage.get_user | def get_user(
self, identified_with, identifier, req, resp, resource, uri_kwargs
):
"""Get user object for given identifier.
Args:
identified_with (object): authentication middleware used
to identify the user.
identifier: middleware specifix user identifier (string or tuple
in case of all built in authentication middleware classes).
Returns:
dict: user object stored in Redis if it exists, otherwise ``None``
"""
stored_value = self.kv_store.get(
self._get_storage_key(identified_with, identifier)
)
if stored_value is not None:
user = self.serialization.loads(stored_value.decode())
else:
user = None
return user | python | def get_user(
self, identified_with, identifier, req, resp, resource, uri_kwargs
):
"""Get user object for given identifier.
Args:
identified_with (object): authentication middleware used
to identify the user.
identifier: middleware specifix user identifier (string or tuple
in case of all built in authentication middleware classes).
Returns:
dict: user object stored in Redis if it exists, otherwise ``None``
"""
stored_value = self.kv_store.get(
self._get_storage_key(identified_with, identifier)
)
if stored_value is not None:
user = self.serialization.loads(stored_value.decode())
else:
user = None
return user | [
"def",
"get_user",
"(",
"self",
",",
"identified_with",
",",
"identifier",
",",
"req",
",",
"resp",
",",
"resource",
",",
"uri_kwargs",
")",
":",
"stored_value",
"=",
"self",
".",
"kv_store",
".",
"get",
"(",
"self",
".",
"_get_storage_key",
"(",
"identifi... | Get user object for given identifier.
Args:
identified_with (object): authentication middleware used
to identify the user.
identifier: middleware specifix user identifier (string or tuple
in case of all built in authentication middleware classes).
Returns:
dict: user object stored in Redis if it exists, otherwise ``None`` | [
"Get",
"user",
"object",
"for",
"given",
"identifier",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L209-L231 | train | 24,169 |
swistakm/graceful | src/graceful/authentication.py | KeyValueUserStorage.register | def register(self, identified_with, identifier, user):
"""Register new key for given client identifier.
This is only a helper method that allows to register new
user objects for client identities (keys, tokens, addresses etc.).
Args:
identified_with (object): authentication middleware used
to identify the user.
identifier (str): user identifier.
user (str): user object to be stored in the backend.
"""
self.kv_store.set(
self._get_storage_key(identified_with, identifier),
self.serialization.dumps(user).encode(),
) | python | def register(self, identified_with, identifier, user):
"""Register new key for given client identifier.
This is only a helper method that allows to register new
user objects for client identities (keys, tokens, addresses etc.).
Args:
identified_with (object): authentication middleware used
to identify the user.
identifier (str): user identifier.
user (str): user object to be stored in the backend.
"""
self.kv_store.set(
self._get_storage_key(identified_with, identifier),
self.serialization.dumps(user).encode(),
) | [
"def",
"register",
"(",
"self",
",",
"identified_with",
",",
"identifier",
",",
"user",
")",
":",
"self",
".",
"kv_store",
".",
"set",
"(",
"self",
".",
"_get_storage_key",
"(",
"identified_with",
",",
"identifier",
")",
",",
"self",
".",
"serialization",
... | Register new key for given client identifier.
This is only a helper method that allows to register new
user objects for client identities (keys, tokens, addresses etc.).
Args:
identified_with (object): authentication middleware used
to identify the user.
identifier (str): user identifier.
user (str): user object to be stored in the backend. | [
"Register",
"new",
"key",
"for",
"given",
"client",
"identifier",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L233-L248 | train | 24,170 |
swistakm/graceful | src/graceful/authentication.py | BaseAuthenticationMiddleware.process_resource | def process_resource(self, req, resp, resource, uri_kwargs=None):
"""Process resource after routing to it.
This is basic falcon middleware handler.
Args:
req (falcon.Request): request object
resp (falcon.Response): response object
resource (object): resource object matched by falcon router
uri_kwargs (dict): additional keyword argument from uri template.
For ``falcon<1.0.0`` this is always ``None``
"""
if 'user' in req.context:
return
identifier = self.identify(req, resp, resource, uri_kwargs)
user = self.try_storage(identifier, req, resp, resource, uri_kwargs)
if user is not None:
req.context['user'] = user
# if did not succeed then we need to add this to list of available
# challenges.
elif self.challenge is not None:
req.context.setdefault(
'challenges', list()
).append(self.challenge) | python | def process_resource(self, req, resp, resource, uri_kwargs=None):
"""Process resource after routing to it.
This is basic falcon middleware handler.
Args:
req (falcon.Request): request object
resp (falcon.Response): response object
resource (object): resource object matched by falcon router
uri_kwargs (dict): additional keyword argument from uri template.
For ``falcon<1.0.0`` this is always ``None``
"""
if 'user' in req.context:
return
identifier = self.identify(req, resp, resource, uri_kwargs)
user = self.try_storage(identifier, req, resp, resource, uri_kwargs)
if user is not None:
req.context['user'] = user
# if did not succeed then we need to add this to list of available
# challenges.
elif self.challenge is not None:
req.context.setdefault(
'challenges', list()
).append(self.challenge) | [
"def",
"process_resource",
"(",
"self",
",",
"req",
",",
"resp",
",",
"resource",
",",
"uri_kwargs",
"=",
"None",
")",
":",
"if",
"'user'",
"in",
"req",
".",
"context",
":",
"return",
"identifier",
"=",
"self",
".",
"identify",
"(",
"req",
",",
"resp",... | Process resource after routing to it.
This is basic falcon middleware handler.
Args:
req (falcon.Request): request object
resp (falcon.Response): response object
resource (object): resource object matched by falcon router
uri_kwargs (dict): additional keyword argument from uri template.
For ``falcon<1.0.0`` this is always ``None`` | [
"Process",
"resource",
"after",
"routing",
"to",
"it",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L288-L314 | train | 24,171 |
swistakm/graceful | src/graceful/authentication.py | BaseAuthenticationMiddleware.try_storage | def try_storage(self, identifier, req, resp, resource, uri_kwargs):
"""Try to find user in configured user storage object.
Args:
identifier: User identifier.
Returns:
user object.
"""
if identifier is None:
user = None
# note: if user_storage is defined, always use it in order to
# authenticate user.
elif self.user_storage is not None:
user = self.user_storage.get_user(
self, identifier, req, resp, resource, uri_kwargs
)
# note: some authentication middleware classes may not require
# to be initialized with their own user_storage. In such
# case this will always authenticate with "syntetic user"
# if there is a valid indentity.
elif self.user_storage is None and not self.only_with_storage:
user = {
'identified_with': self,
'identifier': identifier
}
else: # pragma: nocover
# note: this should not happen if the base class is properly
# initialized. Still, user can skip super().__init__() call.
user = None
return user | python | def try_storage(self, identifier, req, resp, resource, uri_kwargs):
"""Try to find user in configured user storage object.
Args:
identifier: User identifier.
Returns:
user object.
"""
if identifier is None:
user = None
# note: if user_storage is defined, always use it in order to
# authenticate user.
elif self.user_storage is not None:
user = self.user_storage.get_user(
self, identifier, req, resp, resource, uri_kwargs
)
# note: some authentication middleware classes may not require
# to be initialized with their own user_storage. In such
# case this will always authenticate with "syntetic user"
# if there is a valid indentity.
elif self.user_storage is None and not self.only_with_storage:
user = {
'identified_with': self,
'identifier': identifier
}
else: # pragma: nocover
# note: this should not happen if the base class is properly
# initialized. Still, user can skip super().__init__() call.
user = None
return user | [
"def",
"try_storage",
"(",
"self",
",",
"identifier",
",",
"req",
",",
"resp",
",",
"resource",
",",
"uri_kwargs",
")",
":",
"if",
"identifier",
"is",
"None",
":",
"user",
"=",
"None",
"# note: if user_storage is defined, always use it in order to",
"# authent... | Try to find user in configured user storage object.
Args:
identifier: User identifier.
Returns:
user object. | [
"Try",
"to",
"find",
"user",
"in",
"configured",
"user",
"storage",
"object",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L331-L365 | train | 24,172 |
swistakm/graceful | src/graceful/authentication.py | Basic.identify | def identify(self, req, resp, resource, uri_kwargs):
"""Identify user using Authenticate header with Basic auth."""
header = req.get_header("Authorization", False)
auth = header.split(" ") if header else None
if auth is None or auth[0].lower() != 'basic':
return None
if len(auth) != 2:
raise HTTPBadRequest(
"Invalid Authorization header",
"The Authorization header for Basic auth should be in form:\n"
"Authorization: Basic <base64-user-pass>"
)
user_pass = auth[1]
try:
decoded = base64.b64decode(user_pass).decode()
except (TypeError, UnicodeDecodeError, binascii.Error):
raise HTTPBadRequest(
"Invalid Authorization header",
"Credentials for Basic auth not correctly base64 encoded."
)
username, _, password = decoded.partition(":")
return username, password | python | def identify(self, req, resp, resource, uri_kwargs):
"""Identify user using Authenticate header with Basic auth."""
header = req.get_header("Authorization", False)
auth = header.split(" ") if header else None
if auth is None or auth[0].lower() != 'basic':
return None
if len(auth) != 2:
raise HTTPBadRequest(
"Invalid Authorization header",
"The Authorization header for Basic auth should be in form:\n"
"Authorization: Basic <base64-user-pass>"
)
user_pass = auth[1]
try:
decoded = base64.b64decode(user_pass).decode()
except (TypeError, UnicodeDecodeError, binascii.Error):
raise HTTPBadRequest(
"Invalid Authorization header",
"Credentials for Basic auth not correctly base64 encoded."
)
username, _, password = decoded.partition(":")
return username, password | [
"def",
"identify",
"(",
"self",
",",
"req",
",",
"resp",
",",
"resource",
",",
"uri_kwargs",
")",
":",
"header",
"=",
"req",
".",
"get_header",
"(",
"\"Authorization\"",
",",
"False",
")",
"auth",
"=",
"header",
".",
"split",
"(",
"\" \"",
")",
"if",
... | Identify user using Authenticate header with Basic auth. | [
"Identify",
"user",
"using",
"Authenticate",
"header",
"with",
"Basic",
"auth",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L426-L453 | train | 24,173 |
swistakm/graceful | src/graceful/authentication.py | XAPIKey.identify | def identify(self, req, resp, resource, uri_kwargs):
"""Initialize X-Api-Key authentication middleware."""
try:
return req.get_header('X-Api-Key', True)
except (KeyError, HTTPMissingHeader):
pass | python | def identify(self, req, resp, resource, uri_kwargs):
"""Initialize X-Api-Key authentication middleware."""
try:
return req.get_header('X-Api-Key', True)
except (KeyError, HTTPMissingHeader):
pass | [
"def",
"identify",
"(",
"self",
",",
"req",
",",
"resp",
",",
"resource",
",",
"uri_kwargs",
")",
":",
"try",
":",
"return",
"req",
".",
"get_header",
"(",
"'X-Api-Key'",
",",
"True",
")",
"except",
"(",
"KeyError",
",",
"HTTPMissingHeader",
")",
":",
... | Initialize X-Api-Key authentication middleware. | [
"Initialize",
"X",
"-",
"Api",
"-",
"Key",
"authentication",
"middleware",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L490-L495 | train | 24,174 |
swistakm/graceful | src/graceful/authentication.py | Token.identify | def identify(self, req, resp, resource, uri_kwargs):
"""Identify user using Authenticate header with Token auth."""
header = req.get_header('Authorization', False)
auth = header.split(' ') if header else None
if auth is None or auth[0].lower() != 'token':
return None
if len(auth) != 2:
raise HTTPBadRequest(
"Invalid Authorization header",
"The Authorization header for Token auth should be in form:\n"
"Authorization: Token <token_value>"
)
return auth[1] | python | def identify(self, req, resp, resource, uri_kwargs):
"""Identify user using Authenticate header with Token auth."""
header = req.get_header('Authorization', False)
auth = header.split(' ') if header else None
if auth is None or auth[0].lower() != 'token':
return None
if len(auth) != 2:
raise HTTPBadRequest(
"Invalid Authorization header",
"The Authorization header for Token auth should be in form:\n"
"Authorization: Token <token_value>"
)
return auth[1] | [
"def",
"identify",
"(",
"self",
",",
"req",
",",
"resp",
",",
"resource",
",",
"uri_kwargs",
")",
":",
"header",
"=",
"req",
".",
"get_header",
"(",
"'Authorization'",
",",
"False",
")",
"auth",
"=",
"header",
".",
"split",
"(",
"' '",
")",
"if",
"he... | Identify user using Authenticate header with Token auth. | [
"Identify",
"user",
"using",
"Authenticate",
"header",
"with",
"Token",
"auth",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L524-L539 | train | 24,175 |
swistakm/graceful | src/graceful/authentication.py | XForwardedFor._get_client_address | def _get_client_address(self, req):
"""Get address from ``X-Forwarded-For`` header or use remote address.
Remote address is used if the ``X-Forwarded-For`` header is not
available. Note that this may not be safe to depend on both without
proper authorization backend.
Args:
req (falcon.Request): falcon.Request object.
Returns:
str: client address.
"""
try:
forwarded_for = req.get_header('X-Forwarded-For', True)
return forwarded_for.split(',')[0].strip()
except (KeyError, HTTPMissingHeader):
return (
req.env.get('REMOTE_ADDR') if self.remote_address_fallback
else None
) | python | def _get_client_address(self, req):
"""Get address from ``X-Forwarded-For`` header or use remote address.
Remote address is used if the ``X-Forwarded-For`` header is not
available. Note that this may not be safe to depend on both without
proper authorization backend.
Args:
req (falcon.Request): falcon.Request object.
Returns:
str: client address.
"""
try:
forwarded_for = req.get_header('X-Forwarded-For', True)
return forwarded_for.split(',')[0].strip()
except (KeyError, HTTPMissingHeader):
return (
req.env.get('REMOTE_ADDR') if self.remote_address_fallback
else None
) | [
"def",
"_get_client_address",
"(",
"self",
",",
"req",
")",
":",
"try",
":",
"forwarded_for",
"=",
"req",
".",
"get_header",
"(",
"'X-Forwarded-For'",
",",
"True",
")",
"return",
"forwarded_for",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
".",
"strip"... | Get address from ``X-Forwarded-For`` header or use remote address.
Remote address is used if the ``X-Forwarded-For`` header is not
available. Note that this may not be safe to depend on both without
proper authorization backend.
Args:
req (falcon.Request): falcon.Request object.
Returns:
str: client address. | [
"Get",
"address",
"from",
"X",
"-",
"Forwarded",
"-",
"For",
"header",
"or",
"use",
"remote",
"address",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L595-L615 | train | 24,176 |
swistakm/graceful | src/graceful/errors.py | DeserializationError._get_description | def _get_description(self):
"""Return human readable description error description.
This description should explain everything that went wrong during
deserialization.
"""
return ", ".join([
part for part in [
"missing: {}".format(self.missing) if self.missing else "",
(
"forbidden: {}".format(self.forbidden)
if self.forbidden else ""
),
"invalid: {}:".format(self.invalid) if self.invalid else "",
(
"failed to parse: {}".format(self.failed)
if self.failed else ""
)
] if part
]) | python | def _get_description(self):
"""Return human readable description error description.
This description should explain everything that went wrong during
deserialization.
"""
return ", ".join([
part for part in [
"missing: {}".format(self.missing) if self.missing else "",
(
"forbidden: {}".format(self.forbidden)
if self.forbidden else ""
),
"invalid: {}:".format(self.invalid) if self.invalid else "",
(
"failed to parse: {}".format(self.failed)
if self.failed else ""
)
] if part
]) | [
"def",
"_get_description",
"(",
"self",
")",
":",
"return",
"\", \"",
".",
"join",
"(",
"[",
"part",
"for",
"part",
"in",
"[",
"\"missing: {}\"",
".",
"format",
"(",
"self",
".",
"missing",
")",
"if",
"self",
".",
"missing",
"else",
"\"\"",
",",
"(",
... | Return human readable description error description.
This description should explain everything that went wrong during
deserialization. | [
"Return",
"human",
"readable",
"description",
"error",
"description",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/errors.py#L23-L43 | train | 24,177 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/config/kube_config.py | load_kube_config | async def load_kube_config(config_file=None, context=None,
client_configuration=None,
persist_config=True):
"""Loads authentication and cluster information from kube-config file
and stores them in kubernetes.client.configuration.
:param config_file: Name of the kube-config file.
:param context: set the active context. If is set to None, current_context
from config file will be used.
:param client_configuration: The kubernetes.client.Configuration to
set configs to.
:param persist_config: If True, config file will be updated when changed
(e.g GCP token refresh).
"""
if config_file is None:
config_file = KUBE_CONFIG_DEFAULT_LOCATION
loader = _get_kube_config_loader_for_yaml_file(
config_file, active_context=context,
persist_config=persist_config)
if client_configuration is None:
config = type.__call__(Configuration)
await loader.load_and_set(config)
Configuration.set_default(config)
else:
await loader.load_and_set(client_configuration)
return loader | python | async def load_kube_config(config_file=None, context=None,
client_configuration=None,
persist_config=True):
"""Loads authentication and cluster information from kube-config file
and stores them in kubernetes.client.configuration.
:param config_file: Name of the kube-config file.
:param context: set the active context. If is set to None, current_context
from config file will be used.
:param client_configuration: The kubernetes.client.Configuration to
set configs to.
:param persist_config: If True, config file will be updated when changed
(e.g GCP token refresh).
"""
if config_file is None:
config_file = KUBE_CONFIG_DEFAULT_LOCATION
loader = _get_kube_config_loader_for_yaml_file(
config_file, active_context=context,
persist_config=persist_config)
if client_configuration is None:
config = type.__call__(Configuration)
await loader.load_and_set(config)
Configuration.set_default(config)
else:
await loader.load_and_set(client_configuration)
return loader | [
"async",
"def",
"load_kube_config",
"(",
"config_file",
"=",
"None",
",",
"context",
"=",
"None",
",",
"client_configuration",
"=",
"None",
",",
"persist_config",
"=",
"True",
")",
":",
"if",
"config_file",
"is",
"None",
":",
"config_file",
"=",
"KUBE_CONFIG_D... | Loads authentication and cluster information from kube-config file
and stores them in kubernetes.client.configuration.
:param config_file: Name of the kube-config file.
:param context: set the active context. If is set to None, current_context
from config file will be used.
:param client_configuration: The kubernetes.client.Configuration to
set configs to.
:param persist_config: If True, config file will be updated when changed
(e.g GCP token refresh). | [
"Loads",
"authentication",
"and",
"cluster",
"information",
"from",
"kube",
"-",
"config",
"file",
"and",
"stores",
"them",
"in",
"kubernetes",
".",
"client",
".",
"configuration",
"."
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/config/kube_config.py#L533-L561 | train | 24,178 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/config/kube_config.py | refresh_token | async def refresh_token(loader, client_configuration=None, interval=60):
"""Refresh token if necessary, updates the token in client configurarion
:param loader: KubeConfigLoader returned by load_kube_config
:param client_configuration: The kubernetes.client.Configuration to
set configs to.
:param interval: how often check if token is up-to-date
"""
if loader.provider != 'gcp':
return
if client_configuration is None:
client_configuration = Configuration()
while 1:
await asyncio.sleep(interval)
await loader.load_gcp_token()
client_configuration.api_key['authorization'] = loader.token | python | async def refresh_token(loader, client_configuration=None, interval=60):
"""Refresh token if necessary, updates the token in client configurarion
:param loader: KubeConfigLoader returned by load_kube_config
:param client_configuration: The kubernetes.client.Configuration to
set configs to.
:param interval: how often check if token is up-to-date
"""
if loader.provider != 'gcp':
return
if client_configuration is None:
client_configuration = Configuration()
while 1:
await asyncio.sleep(interval)
await loader.load_gcp_token()
client_configuration.api_key['authorization'] = loader.token | [
"async",
"def",
"refresh_token",
"(",
"loader",
",",
"client_configuration",
"=",
"None",
",",
"interval",
"=",
"60",
")",
":",
"if",
"loader",
".",
"provider",
"!=",
"'gcp'",
":",
"return",
"if",
"client_configuration",
"is",
"None",
":",
"client_configuratio... | Refresh token if necessary, updates the token in client configurarion
:param loader: KubeConfigLoader returned by load_kube_config
:param client_configuration: The kubernetes.client.Configuration to
set configs to.
:param interval: how often check if token is up-to-date | [
"Refresh",
"token",
"if",
"necessary",
"updates",
"the",
"token",
"in",
"client",
"configurarion"
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/config/kube_config.py#L564-L582 | train | 24,179 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/config/kube_config.py | new_client_from_config | async def new_client_from_config(config_file=None, context=None, persist_config=True):
"""Loads configuration the same as load_kube_config but returns an ApiClient
to be used with any API object. This will allow the caller to concurrently
talk with multiple clusters."""
client_config = type.__call__(Configuration)
await load_kube_config(config_file=config_file, context=context,
client_configuration=client_config,
persist_config=persist_config)
return ApiClient(configuration=client_config) | python | async def new_client_from_config(config_file=None, context=None, persist_config=True):
"""Loads configuration the same as load_kube_config but returns an ApiClient
to be used with any API object. This will allow the caller to concurrently
talk with multiple clusters."""
client_config = type.__call__(Configuration)
await load_kube_config(config_file=config_file, context=context,
client_configuration=client_config,
persist_config=persist_config)
return ApiClient(configuration=client_config) | [
"async",
"def",
"new_client_from_config",
"(",
"config_file",
"=",
"None",
",",
"context",
"=",
"None",
",",
"persist_config",
"=",
"True",
")",
":",
"client_config",
"=",
"type",
".",
"__call__",
"(",
"Configuration",
")",
"await",
"load_kube_config",
"(",
"c... | Loads configuration the same as load_kube_config but returns an ApiClient
to be used with any API object. This will allow the caller to concurrently
talk with multiple clusters. | [
"Loads",
"configuration",
"the",
"same",
"as",
"load_kube_config",
"but",
"returns",
"an",
"ApiClient",
"to",
"be",
"used",
"with",
"any",
"API",
"object",
".",
"This",
"will",
"allow",
"the",
"caller",
"to",
"concurrently",
"talk",
"with",
"multiple",
"cluste... | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/config/kube_config.py#L585-L595 | train | 24,180 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/config/kube_config.py | KubeConfigLoader._load_authentication | async def _load_authentication(self):
"""Read authentication from kube-config user section if exists.
This function goes through various authentication methods in user
section of kube-config and stops if it finds a valid authentication
method. The order of authentication methods is:
1. GCP auth-provider
2. token field (point to a token file)
3. oidc auth-provider
4. exec provided plugin
5. username/password
"""
if not self._user:
logging.debug('No user section in current context.')
return
if self.provider == 'gcp':
await self.load_gcp_token()
return
if self.provider == PROVIDER_TYPE_OIDC:
await self._load_oid_token()
return
if 'exec' in self._user:
logging.debug('Try to use exec provider')
res_exec_plugin = await self._load_from_exec_plugin()
if res_exec_plugin:
return
logging.debug('Try to load user token')
if self._load_user_token():
return
logging.debug('Try to use username and password')
self._load_user_pass_token() | python | async def _load_authentication(self):
"""Read authentication from kube-config user section if exists.
This function goes through various authentication methods in user
section of kube-config and stops if it finds a valid authentication
method. The order of authentication methods is:
1. GCP auth-provider
2. token field (point to a token file)
3. oidc auth-provider
4. exec provided plugin
5. username/password
"""
if not self._user:
logging.debug('No user section in current context.')
return
if self.provider == 'gcp':
await self.load_gcp_token()
return
if self.provider == PROVIDER_TYPE_OIDC:
await self._load_oid_token()
return
if 'exec' in self._user:
logging.debug('Try to use exec provider')
res_exec_plugin = await self._load_from_exec_plugin()
if res_exec_plugin:
return
logging.debug('Try to load user token')
if self._load_user_token():
return
logging.debug('Try to use username and password')
self._load_user_pass_token() | [
"async",
"def",
"_load_authentication",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_user",
":",
"logging",
".",
"debug",
"(",
"'No user section in current context.'",
")",
"return",
"if",
"self",
".",
"provider",
"==",
"'gcp'",
":",
"await",
"self",
"... | Read authentication from kube-config user section if exists.
This function goes through various authentication methods in user
section of kube-config and stops if it finds a valid authentication
method. The order of authentication methods is:
1. GCP auth-provider
2. token field (point to a token file)
3. oidc auth-provider
4. exec provided plugin
5. username/password | [
"Read",
"authentication",
"from",
"kube",
"-",
"config",
"user",
"section",
"if",
"exists",
"."
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/config/kube_config.py#L178-L215 | train | 24,181 |
swistakm/graceful | src/graceful/validators.py | min_validator | def min_validator(min_value):
"""Return validator function that ensures lower bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check
Args:
min_value: minimal value for new validator
"""
def validator(value):
if value < min_value:
raise ValidationError("{} is not >= {}".format(value, min_value))
return validator | python | def min_validator(min_value):
"""Return validator function that ensures lower bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check
Args:
min_value: minimal value for new validator
"""
def validator(value):
if value < min_value:
raise ValidationError("{} is not >= {}".format(value, min_value))
return validator | [
"def",
"min_validator",
"(",
"min_value",
")",
":",
"def",
"validator",
"(",
"value",
")",
":",
"if",
"value",
"<",
"min_value",
":",
"raise",
"ValidationError",
"(",
"\"{} is not >= {}\"",
".",
"format",
"(",
"value",
",",
"min_value",
")",
")",
"return",
... | Return validator function that ensures lower bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check
Args:
min_value: minimal value for new validator | [
"Return",
"validator",
"function",
"that",
"ensures",
"lower",
"bound",
"of",
"a",
"number",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L14-L28 | train | 24,182 |
swistakm/graceful | src/graceful/validators.py | max_validator | def max_validator(max_value):
"""Return validator function that ensures upper bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check.
Args:
max_value: maximum value for new validator
"""
def validator(value):
if value > max_value:
raise ValidationError("{} is not <= {}".format(value, max_value))
return validator | python | def max_validator(max_value):
"""Return validator function that ensures upper bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check.
Args:
max_value: maximum value for new validator
"""
def validator(value):
if value > max_value:
raise ValidationError("{} is not <= {}".format(value, max_value))
return validator | [
"def",
"max_validator",
"(",
"max_value",
")",
":",
"def",
"validator",
"(",
"value",
")",
":",
"if",
"value",
">",
"max_value",
":",
"raise",
"ValidationError",
"(",
"\"{} is not <= {}\"",
".",
"format",
"(",
"value",
",",
"max_value",
")",
")",
"return",
... | Return validator function that ensures upper bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check.
Args:
max_value: maximum value for new validator | [
"Return",
"validator",
"function",
"that",
"ensures",
"upper",
"bound",
"of",
"a",
"number",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L31-L45 | train | 24,183 |
swistakm/graceful | src/graceful/validators.py | choices_validator | def choices_validator(choices):
"""Return validator function that will check if ``value in choices``.
Args:
max_value (list, set, tuple): allowed choices for new validator
"""
def validator(value):
if value not in choices:
# note: make it a list for consistent representation
raise ValidationError(
"{} is not in {}".format(value, list(choices))
)
return validator | python | def choices_validator(choices):
"""Return validator function that will check if ``value in choices``.
Args:
max_value (list, set, tuple): allowed choices for new validator
"""
def validator(value):
if value not in choices:
# note: make it a list for consistent representation
raise ValidationError(
"{} is not in {}".format(value, list(choices))
)
return validator | [
"def",
"choices_validator",
"(",
"choices",
")",
":",
"def",
"validator",
"(",
"value",
")",
":",
"if",
"value",
"not",
"in",
"choices",
":",
"# note: make it a list for consistent representation",
"raise",
"ValidationError",
"(",
"\"{} is not in {}\"",
".",
"format",... | Return validator function that will check if ``value in choices``.
Args:
max_value (list, set, tuple): allowed choices for new validator | [
"Return",
"validator",
"function",
"that",
"will",
"check",
"if",
"value",
"in",
"choices",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L48-L62 | train | 24,184 |
swistakm/graceful | src/graceful/validators.py | match_validator | def match_validator(expression):
"""Return validator function that will check if matches given expression.
Args:
match: if string then this will be converted to regular expression
using ``re.compile``. Can be also any object that has ``match()``
method like already compiled regular regular expression or custom
matching object/class.
"""
if isinstance(expression, str):
compiled = re.compile(expression)
elif hasattr(expression, 'match'):
# check it early so we could say something is wrong early
compiled = expression
else:
raise TypeError(
'Provided match is nor a string nor has a match method '
'(like re expressions)'
)
def validator(value):
if not compiled.match(value):
# note: make it a list for consistent representation
raise ValidationError(
"{} does not match pattern: {}".format(
value,
compiled.pattern
if hasattr(compiled, 'pattern')
else compiled
)
)
return validator | python | def match_validator(expression):
"""Return validator function that will check if matches given expression.
Args:
match: if string then this will be converted to regular expression
using ``re.compile``. Can be also any object that has ``match()``
method like already compiled regular regular expression or custom
matching object/class.
"""
if isinstance(expression, str):
compiled = re.compile(expression)
elif hasattr(expression, 'match'):
# check it early so we could say something is wrong early
compiled = expression
else:
raise TypeError(
'Provided match is nor a string nor has a match method '
'(like re expressions)'
)
def validator(value):
if not compiled.match(value):
# note: make it a list for consistent representation
raise ValidationError(
"{} does not match pattern: {}".format(
value,
compiled.pattern
if hasattr(compiled, 'pattern')
else compiled
)
)
return validator | [
"def",
"match_validator",
"(",
"expression",
")",
":",
"if",
"isinstance",
"(",
"expression",
",",
"str",
")",
":",
"compiled",
"=",
"re",
".",
"compile",
"(",
"expression",
")",
"elif",
"hasattr",
"(",
"expression",
",",
"'match'",
")",
":",
"# check it e... | Return validator function that will check if matches given expression.
Args:
match: if string then this will be converted to regular expression
using ``re.compile``. Can be also any object that has ``match()``
method like already compiled regular regular expression or custom
matching object/class. | [
"Return",
"validator",
"function",
"that",
"will",
"check",
"if",
"matches",
"given",
"expression",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L65-L98 | train | 24,185 |
swistakm/graceful | src/graceful/parameters.py | BaseParam.validated_value | def validated_value(self, raw_value):
"""Return parsed parameter value and run validation handlers.
Error message included in exception will be included in http error
response
Args:
value: raw parameter value to parse validate
Returns:
None
Note:
Concept of validation for params is understood here as a process
of checking if data of valid type (successfully parsed/processed by
``.value()`` handler) does meet some other constraints
(lenght, bounds, uniqueness, etc.). It will internally call its
``value()`` handler.
"""
value = self.value(raw_value)
try:
for validator in self.validators:
validator(value)
except:
raise
else:
return value | python | def validated_value(self, raw_value):
"""Return parsed parameter value and run validation handlers.
Error message included in exception will be included in http error
response
Args:
value: raw parameter value to parse validate
Returns:
None
Note:
Concept of validation for params is understood here as a process
of checking if data of valid type (successfully parsed/processed by
``.value()`` handler) does meet some other constraints
(lenght, bounds, uniqueness, etc.). It will internally call its
``value()`` handler.
"""
value = self.value(raw_value)
try:
for validator in self.validators:
validator(value)
except:
raise
else:
return value | [
"def",
"validated_value",
"(",
"self",
",",
"raw_value",
")",
":",
"value",
"=",
"self",
".",
"value",
"(",
"raw_value",
")",
"try",
":",
"for",
"validator",
"in",
"self",
".",
"validators",
":",
"validator",
"(",
"value",
")",
"except",
":",
"raise",
... | Return parsed parameter value and run validation handlers.
Error message included in exception will be included in http error
response
Args:
value: raw parameter value to parse validate
Returns:
None
Note:
Concept of validation for params is understood here as a process
of checking if data of valid type (successfully parsed/processed by
``.value()`` handler) does meet some other constraints
(lenght, bounds, uniqueness, etc.). It will internally call its
``value()`` handler. | [
"Return",
"parsed",
"parameter",
"value",
"and",
"run",
"validation",
"handlers",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/parameters.py#L122-L149 | train | 24,186 |
swistakm/graceful | src/graceful/parameters.py | BaseParam.describe | def describe(self, **kwargs):
"""Describe this parameter instance for purpose of self-documentation.
Args:
kwargs (dict): dictionary of additional description items for
extending default description
Returns:
dict: dictionary of description items
Suggested way for overriding description fields or extending it with
additional items is calling super class method with new/overriden
fields passed as keyword arguments like following:
.. code-block:: python
class DummyParam(BaseParam):
def description(self, **kwargs):
super().describe(is_dummy=True, **kwargs)
"""
description = {
'label': self.label,
# note: details are expected to be large so it should
# be reformatted
'details': inspect.cleandoc(self.details),
'required': self.required,
'many': self.many,
'spec': self.spec,
'default': self.default,
'type': self.type or 'unspecified'
}
description.update(kwargs)
return description | python | def describe(self, **kwargs):
"""Describe this parameter instance for purpose of self-documentation.
Args:
kwargs (dict): dictionary of additional description items for
extending default description
Returns:
dict: dictionary of description items
Suggested way for overriding description fields or extending it with
additional items is calling super class method with new/overriden
fields passed as keyword arguments like following:
.. code-block:: python
class DummyParam(BaseParam):
def description(self, **kwargs):
super().describe(is_dummy=True, **kwargs)
"""
description = {
'label': self.label,
# note: details are expected to be large so it should
# be reformatted
'details': inspect.cleandoc(self.details),
'required': self.required,
'many': self.many,
'spec': self.spec,
'default': self.default,
'type': self.type or 'unspecified'
}
description.update(kwargs)
return description | [
"def",
"describe",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"description",
"=",
"{",
"'label'",
":",
"self",
".",
"label",
",",
"# note: details are expected to be large so it should",
"# be reformatted",
"'details'",
":",
"inspect",
".",
"cleandoc",
... | Describe this parameter instance for purpose of self-documentation.
Args:
kwargs (dict): dictionary of additional description items for
extending default description
Returns:
dict: dictionary of description items
Suggested way for overriding description fields or extending it with
additional items is calling super class method with new/overriden
fields passed as keyword arguments like following:
.. code-block:: python
class DummyParam(BaseParam):
def description(self, **kwargs):
super().describe(is_dummy=True, **kwargs) | [
"Describe",
"this",
"parameter",
"instance",
"for",
"purpose",
"of",
"self",
"-",
"documentation",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/parameters.py#L164-L199 | train | 24,187 |
swistakm/graceful | src/graceful/parameters.py | Base64EncodedParam.value | def value(self, raw_value):
"""Decode param with Base64."""
try:
return base64.b64decode(bytes(raw_value, 'utf-8')).decode('utf-8')
except binascii.Error as err:
raise ValueError(str(err)) | python | def value(self, raw_value):
"""Decode param with Base64."""
try:
return base64.b64decode(bytes(raw_value, 'utf-8')).decode('utf-8')
except binascii.Error as err:
raise ValueError(str(err)) | [
"def",
"value",
"(",
"self",
",",
"raw_value",
")",
":",
"try",
":",
"return",
"base64",
".",
"b64decode",
"(",
"bytes",
"(",
"raw_value",
",",
"'utf-8'",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"binascii",
".",
"Error",
"as",
"err",
... | Decode param with Base64. | [
"Decode",
"param",
"with",
"Base64",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/parameters.py#L237-L242 | train | 24,188 |
swistakm/graceful | src/graceful/parameters.py | DecimalParam.value | def value(self, raw_value):
"""Decode param as decimal value."""
try:
return decimal.Decimal(raw_value)
except decimal.InvalidOperation:
raise ValueError(
"Could not parse '{}' value as decimal".format(raw_value)
) | python | def value(self, raw_value):
"""Decode param as decimal value."""
try:
return decimal.Decimal(raw_value)
except decimal.InvalidOperation:
raise ValueError(
"Could not parse '{}' value as decimal".format(raw_value)
) | [
"def",
"value",
"(",
"self",
",",
"raw_value",
")",
":",
"try",
":",
"return",
"decimal",
".",
"Decimal",
"(",
"raw_value",
")",
"except",
"decimal",
".",
"InvalidOperation",
":",
"raise",
"ValueError",
"(",
"\"Could not parse '{}' value as decimal\"",
".",
"for... | Decode param as decimal value. | [
"Decode",
"param",
"as",
"decimal",
"value",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/parameters.py#L270-L277 | train | 24,189 |
swistakm/graceful | src/graceful/parameters.py | BoolParam.value | def value(self, raw_value):
"""Decode param as bool value."""
if raw_value in self._FALSE_VALUES:
return False
elif raw_value in self._TRUE_VALUES:
return True
else:
raise ValueError(
"Could not parse '{}' value as boolean".format(raw_value)
) | python | def value(self, raw_value):
"""Decode param as bool value."""
if raw_value in self._FALSE_VALUES:
return False
elif raw_value in self._TRUE_VALUES:
return True
else:
raise ValueError(
"Could not parse '{}' value as boolean".format(raw_value)
) | [
"def",
"value",
"(",
"self",
",",
"raw_value",
")",
":",
"if",
"raw_value",
"in",
"self",
".",
"_FALSE_VALUES",
":",
"return",
"False",
"elif",
"raw_value",
"in",
"self",
".",
"_TRUE_VALUES",
":",
"return",
"True",
"else",
":",
"raise",
"ValueError",
"(",
... | Decode param as bool value. | [
"Decode",
"param",
"as",
"bool",
"value",
"."
] | d4678cb6349a5c843a5e58002fc80140821609e4 | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/parameters.py#L300-L309 | train | 24,190 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/models/v1beta1_certificate_signing_request_spec.py | V1beta1CertificateSigningRequestSpec.request | def request(self, request):
"""Sets the request of this V1beta1CertificateSigningRequestSpec.
Base64-encoded PKCS#10 CSR data # noqa: E501
:param request: The request of this V1beta1CertificateSigningRequestSpec. # noqa: E501
:type: str
"""
if request is None:
raise ValueError("Invalid value for `request`, must not be `None`") # noqa: E501
if request is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', request): # noqa: E501
raise ValueError(r"Invalid value for `request`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501
self._request = request | python | def request(self, request):
"""Sets the request of this V1beta1CertificateSigningRequestSpec.
Base64-encoded PKCS#10 CSR data # noqa: E501
:param request: The request of this V1beta1CertificateSigningRequestSpec. # noqa: E501
:type: str
"""
if request is None:
raise ValueError("Invalid value for `request`, must not be `None`") # noqa: E501
if request is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', request): # noqa: E501
raise ValueError(r"Invalid value for `request`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501
self._request = request | [
"def",
"request",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `request`, must not be `None`\"",
")",
"# noqa: E501",
"if",
"request",
"is",
"not",
"None",
"and",
"not",
"re",
".",
... | Sets the request of this V1beta1CertificateSigningRequestSpec.
Base64-encoded PKCS#10 CSR data # noqa: E501
:param request: The request of this V1beta1CertificateSigningRequestSpec. # noqa: E501
:type: str | [
"Sets",
"the",
"request",
"of",
"this",
"V1beta1CertificateSigningRequestSpec",
"."
] | f9ab15317ec921409714c7afef11aeb0f579985d | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/models/v1beta1_certificate_signing_request_spec.py#L132-L145 | train | 24,191 |
CLARIAH/grlc | src/projection.py | project | def project(dataIn, projectionScript):
'''Programs may make use of data in the `dataIn` variable and should
produce data on the `dataOut` variable.'''
# We don't really need to initialize it, but we do it to avoid linter errors
dataOut = {}
try:
projectionScript = str(projectionScript)
program = makeProgramFromString(projectionScript)
if PY3:
loc = {
'dataIn': dataIn,
'dataOut': dataOut
}
exec(program, {}, loc)
dataOut = loc['dataOut']
else:
exec(program)
except Exception as e:
glogger.error("Error while executing SPARQL projection")
glogger.error(projectionScript)
glogger.error("Encountered exception: ")
glogger.error(e)
dataOut = {
'status': 'error',
'message': e.message
}
return dataOut | python | def project(dataIn, projectionScript):
'''Programs may make use of data in the `dataIn` variable and should
produce data on the `dataOut` variable.'''
# We don't really need to initialize it, but we do it to avoid linter errors
dataOut = {}
try:
projectionScript = str(projectionScript)
program = makeProgramFromString(projectionScript)
if PY3:
loc = {
'dataIn': dataIn,
'dataOut': dataOut
}
exec(program, {}, loc)
dataOut = loc['dataOut']
else:
exec(program)
except Exception as e:
glogger.error("Error while executing SPARQL projection")
glogger.error(projectionScript)
glogger.error("Encountered exception: ")
glogger.error(e)
dataOut = {
'status': 'error',
'message': e.message
}
return dataOut | [
"def",
"project",
"(",
"dataIn",
",",
"projectionScript",
")",
":",
"# We don't really need to initialize it, but we do it to avoid linter errors",
"dataOut",
"=",
"{",
"}",
"try",
":",
"projectionScript",
"=",
"str",
"(",
"projectionScript",
")",
"program",
"=",
"makeP... | Programs may make use of data in the `dataIn` variable and should
produce data on the `dataOut` variable. | [
"Programs",
"may",
"make",
"use",
"of",
"data",
"in",
"the",
"dataIn",
"variable",
"and",
"should",
"produce",
"data",
"on",
"the",
"dataOut",
"variable",
"."
] | f5664e34f039010c00ef8ebb69917c05e8ce75d7 | https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/projection.py#L7-L33 | train | 24,192 |
CLARIAH/grlc | src/prov.py | grlcPROV.init_prov_graph | def init_prov_graph(self):
"""
Initialize PROV graph with all we know at the start of the recording
"""
try:
# Use git2prov to get prov on the repo
repo_prov = check_output(
['node_modules/git2prov/bin/git2prov', 'https://github.com/{}/{}/'.format(self.user, self.repo),
'PROV-O']).decode("utf-8")
repo_prov = repo_prov[repo_prov.find('@'):]
# glogger.debug('Git2PROV output: {}'.format(repo_prov))
glogger.debug('Ingesting Git2PROV output into RDF graph')
with open('temp.prov.ttl', 'w') as temp_prov:
temp_prov.write(repo_prov)
self.prov_g.parse('temp.prov.ttl', format='turtle')
except Exception as e:
glogger.error(e)
glogger.error("Couldn't parse Git2PROV graph, continuing without repo PROV")
pass
self.prov_g.add((self.agent, RDF.type, self.prov.Agent))
self.prov_g.add((self.entity_d, RDF.type, self.prov.Entity))
self.prov_g.add((self.activity, RDF.type, self.prov.Activity))
# entity_d
self.prov_g.add((self.entity_d, self.prov.wasGeneratedBy, self.activity))
self.prov_g.add((self.entity_d, self.prov.wasAttributedTo, self.agent))
# later: entity_d genereated at time (when we know the end time)
# activity
self.prov_g.add((self.activity, self.prov.wasAssociatedWith, self.agent))
self.prov_g.add((self.activity, self.prov.startedAtTime, Literal(datetime.now()))) | python | def init_prov_graph(self):
"""
Initialize PROV graph with all we know at the start of the recording
"""
try:
# Use git2prov to get prov on the repo
repo_prov = check_output(
['node_modules/git2prov/bin/git2prov', 'https://github.com/{}/{}/'.format(self.user, self.repo),
'PROV-O']).decode("utf-8")
repo_prov = repo_prov[repo_prov.find('@'):]
# glogger.debug('Git2PROV output: {}'.format(repo_prov))
glogger.debug('Ingesting Git2PROV output into RDF graph')
with open('temp.prov.ttl', 'w') as temp_prov:
temp_prov.write(repo_prov)
self.prov_g.parse('temp.prov.ttl', format='turtle')
except Exception as e:
glogger.error(e)
glogger.error("Couldn't parse Git2PROV graph, continuing without repo PROV")
pass
self.prov_g.add((self.agent, RDF.type, self.prov.Agent))
self.prov_g.add((self.entity_d, RDF.type, self.prov.Entity))
self.prov_g.add((self.activity, RDF.type, self.prov.Activity))
# entity_d
self.prov_g.add((self.entity_d, self.prov.wasGeneratedBy, self.activity))
self.prov_g.add((self.entity_d, self.prov.wasAttributedTo, self.agent))
# later: entity_d genereated at time (when we know the end time)
# activity
self.prov_g.add((self.activity, self.prov.wasAssociatedWith, self.agent))
self.prov_g.add((self.activity, self.prov.startedAtTime, Literal(datetime.now()))) | [
"def",
"init_prov_graph",
"(",
"self",
")",
":",
"try",
":",
"# Use git2prov to get prov on the repo",
"repo_prov",
"=",
"check_output",
"(",
"[",
"'node_modules/git2prov/bin/git2prov'",
",",
"'https://github.com/{}/{}/'",
".",
"format",
"(",
"self",
".",
"user",
",",
... | Initialize PROV graph with all we know at the start of the recording | [
"Initialize",
"PROV",
"graph",
"with",
"all",
"we",
"know",
"at",
"the",
"start",
"of",
"the",
"recording"
] | f5664e34f039010c00ef8ebb69917c05e8ce75d7 | https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/prov.py#L35-L68 | train | 24,193 |
CLARIAH/grlc | src/prov.py | grlcPROV.add_used_entity | def add_used_entity(self, entity_uri):
"""
Add the provided URI as a used entity by the logged activity
"""
entity_o = URIRef(entity_uri)
self.prov_g.add((entity_o, RDF.type, self.prov.Entity))
self.prov_g.add((self.activity, self.prov.used, entity_o)) | python | def add_used_entity(self, entity_uri):
"""
Add the provided URI as a used entity by the logged activity
"""
entity_o = URIRef(entity_uri)
self.prov_g.add((entity_o, RDF.type, self.prov.Entity))
self.prov_g.add((self.activity, self.prov.used, entity_o)) | [
"def",
"add_used_entity",
"(",
"self",
",",
"entity_uri",
")",
":",
"entity_o",
"=",
"URIRef",
"(",
"entity_uri",
")",
"self",
".",
"prov_g",
".",
"add",
"(",
"(",
"entity_o",
",",
"RDF",
".",
"type",
",",
"self",
".",
"prov",
".",
"Entity",
")",
")"... | Add the provided URI as a used entity by the logged activity | [
"Add",
"the",
"provided",
"URI",
"as",
"a",
"used",
"entity",
"by",
"the",
"logged",
"activity"
] | f5664e34f039010c00ef8ebb69917c05e8ce75d7 | https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/prov.py#L72-L78 | train | 24,194 |
CLARIAH/grlc | src/prov.py | grlcPROV.end_prov_graph | def end_prov_graph(self):
"""
Finalize prov recording with end time
"""
endTime = Literal(datetime.now())
self.prov_g.add((self.entity_d, self.prov.generatedAtTime, endTime))
self.prov_g.add((self.activity, self.prov.endedAtTime, endTime)) | python | def end_prov_graph(self):
"""
Finalize prov recording with end time
"""
endTime = Literal(datetime.now())
self.prov_g.add((self.entity_d, self.prov.generatedAtTime, endTime))
self.prov_g.add((self.activity, self.prov.endedAtTime, endTime)) | [
"def",
"end_prov_graph",
"(",
"self",
")",
":",
"endTime",
"=",
"Literal",
"(",
"datetime",
".",
"now",
"(",
")",
")",
"self",
".",
"prov_g",
".",
"add",
"(",
"(",
"self",
".",
"entity_d",
",",
"self",
".",
"prov",
".",
"generatedAtTime",
",",
"endTi... | Finalize prov recording with end time | [
"Finalize",
"prov",
"recording",
"with",
"end",
"time"
] | f5664e34f039010c00ef8ebb69917c05e8ce75d7 | https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/prov.py#L80-L86 | train | 24,195 |
CLARIAH/grlc | src/prov.py | grlcPROV.log_prov_graph | def log_prov_graph(self):
"""
Log provenance graph so far
"""
glogger.debug("Spec generation provenance graph:")
glogger.debug(self.prov_g.serialize(format='turtle')) | python | def log_prov_graph(self):
"""
Log provenance graph so far
"""
glogger.debug("Spec generation provenance graph:")
glogger.debug(self.prov_g.serialize(format='turtle')) | [
"def",
"log_prov_graph",
"(",
"self",
")",
":",
"glogger",
".",
"debug",
"(",
"\"Spec generation provenance graph:\"",
")",
"glogger",
".",
"debug",
"(",
"self",
".",
"prov_g",
".",
"serialize",
"(",
"format",
"=",
"'turtle'",
")",
")"
] | Log provenance graph so far | [
"Log",
"provenance",
"graph",
"so",
"far"
] | f5664e34f039010c00ef8ebb69917c05e8ce75d7 | https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/prov.py#L88-L93 | train | 24,196 |
CLARIAH/grlc | src/prov.py | grlcPROV.serialize | def serialize(self, format):
"""
Serialize provenance graph in the specified format
"""
if PY3:
return self.prov_g.serialize(format=format).decode('utf-8')
else:
return self.prov_g.serialize(format=format) | python | def serialize(self, format):
"""
Serialize provenance graph in the specified format
"""
if PY3:
return self.prov_g.serialize(format=format).decode('utf-8')
else:
return self.prov_g.serialize(format=format) | [
"def",
"serialize",
"(",
"self",
",",
"format",
")",
":",
"if",
"PY3",
":",
"return",
"self",
".",
"prov_g",
".",
"serialize",
"(",
"format",
"=",
"format",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"return",
"self",
".",
"prov_g",
".",
... | Serialize provenance graph in the specified format | [
"Serialize",
"provenance",
"graph",
"in",
"the",
"specified",
"format"
] | f5664e34f039010c00ef8ebb69917c05e8ce75d7 | https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/prov.py#L95-L102 | train | 24,197 |
CLARIAH/grlc | src/gquery.py | get_defaults | def get_defaults(rq, v, metadata):
"""
Returns the default value for a parameter or None
"""
glogger.debug("Metadata with defaults: {}".format(metadata))
if 'defaults' not in metadata:
return None
defaultsDict = _getDictWithKey(v, metadata['defaults'])
if defaultsDict:
return defaultsDict[v]
return None | python | def get_defaults(rq, v, metadata):
"""
Returns the default value for a parameter or None
"""
glogger.debug("Metadata with defaults: {}".format(metadata))
if 'defaults' not in metadata:
return None
defaultsDict = _getDictWithKey(v, metadata['defaults'])
if defaultsDict:
return defaultsDict[v]
return None | [
"def",
"get_defaults",
"(",
"rq",
",",
"v",
",",
"metadata",
")",
":",
"glogger",
".",
"debug",
"(",
"\"Metadata with defaults: {}\"",
".",
"format",
"(",
"metadata",
")",
")",
"if",
"'defaults'",
"not",
"in",
"metadata",
":",
"return",
"None",
"defaultsDict... | Returns the default value for a parameter or None | [
"Returns",
"the",
"default",
"value",
"for",
"a",
"parameter",
"or",
"None"
] | f5664e34f039010c00ef8ebb69917c05e8ce75d7 | https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/gquery.py#L183-L193 | train | 24,198 |
CLARIAH/grlc | src/fileLoaders.py | LocalLoader.fetchFiles | def fetchFiles(self):
"""Returns a list of file items contained on the local repo."""
print("Fetching files from {}".format(self.baseDir))
files = glob(path.join(self.baseDir, '*'))
filesDef = []
for f in files:
print("Found SPARQL file {}".format(f))
relative = f.replace(self.baseDir, '')
filesDef.append({
'download_url': relative,
'name': relative
})
return filesDef | python | def fetchFiles(self):
"""Returns a list of file items contained on the local repo."""
print("Fetching files from {}".format(self.baseDir))
files = glob(path.join(self.baseDir, '*'))
filesDef = []
for f in files:
print("Found SPARQL file {}".format(f))
relative = f.replace(self.baseDir, '')
filesDef.append({
'download_url': relative,
'name': relative
})
return filesDef | [
"def",
"fetchFiles",
"(",
"self",
")",
":",
"print",
"(",
"\"Fetching files from {}\"",
".",
"format",
"(",
"self",
".",
"baseDir",
")",
")",
"files",
"=",
"glob",
"(",
"path",
".",
"join",
"(",
"self",
".",
"baseDir",
",",
"'*'",
")",
")",
"filesDef",... | Returns a list of file items contained on the local repo. | [
"Returns",
"a",
"list",
"of",
"file",
"items",
"contained",
"on",
"the",
"local",
"repo",
"."
] | f5664e34f039010c00ef8ebb69917c05e8ce75d7 | https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/fileLoaders.py#L125-L137 | train | 24,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.