signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def getType(self, short=False):
if self.isOrigin():<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>t = []<EOL>onAxis = self.isOnAxis()<EOL>if onAxis is False:<EOL><INDENT>if short:<EOL><INDENT>t.append("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>t.append("<STR_LIT>"+ "<STR_LIT:U+0020>".join(self.getActiveAxes()))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if s...
Return a string describing the type of the location, i.e. origin, on axis, off axis etc. :: >>> l = Location() >>> l.getType() 'origin' >>> l = Location(pop=1) >>> l.getType() 'on-axis, pop' >>> l = Location(pop=1, snap=1) ...
f11945:c0:m6
def getActiveAxes(self):
names = sorted(k for k in self.keys() if self[k]!=<NUM_LIT:0>)<EOL>return names<EOL>
Return a list of names of axes which are not zero :: >>> l = Location(pop=1, snap=0, crackle=1) >>> l.getActiveAxes() ['crackle', 'pop']
f11945:c0:m7
def asString(self, strict=False):
if len(self.keys())==<NUM_LIT:0>:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>v = []<EOL>n = []<EOL>try:<EOL><INDENT>for name, value in self.asTuple():<EOL><INDENT>s = '<STR_LIT>'<EOL>if value is None:<EOL><INDENT>s = "<STR_LIT:None>"<EOL><DEDENT>elif type(value) == tuple or type(value) == list:<EOL><INDENT>s = "<STR_LI...
Return the location as a string. :: >>> l = Location(pop=1, snap=(-100.0, -200)) >>> l.asString() 'pop:1, snap:(-100.000,-200.000)'
f11945:c0:m8
def asDict(self):
new = {}<EOL>new.update(self)<EOL>return new<EOL>
Return the location as a plain python dict. :: >>> l = Location(pop=1, snap=-100) >>> l.asDict()['snap'] -100 >>> l.asDict()['pop'] 1
f11945:c0:m9
def asSortedStringDict(self, roundValue=False):
data = []<EOL>names = sorted(self.keys())<EOL>for n in names:<EOL><INDENT>data.append({'<STR_LIT>':n, '<STR_LIT:value>':numberToString(self[n])})<EOL><DEDENT>return data<EOL>
Return the data in a dict with sorted names and column titles. :: >>> l = Location(pop=1, snap=(1,10)) >>> l.asSortedStringDict()[0]['value'] '1' >>> l.asSortedStringDict()[0]['axis'] 'pop' >>> l.asSortedStringDict()[1]['axis'] ...
f11945:c0:m10
def strip(self):
result = []<EOL>for k, v in self.items():<EOL><INDENT>if isinstance(v, tuple):<EOL><INDENT>if v > (_EPSILON, ) * len(v) or v < (-_EPSILON, ) * len(v):<EOL><INDENT>result.append((k, v))<EOL><DEDENT><DEDENT>elif v > _EPSILON or v < -_EPSILON:<EOL><INDENT>result.append((k, v))<EOL><DEDENT><DEDENT>return self.__class__(res...
Remove coordinates that are zero, the opposite of expand(). :: >>> l = Location(pop=1, snap=0) >>> l.strip() <Location pop:1 >
f11945:c0:m11
def common(self, other):
selfDim = set(self.keys())<EOL>otherDim = set(other.keys())<EOL>dims = selfDim | otherDim<EOL>newSelf = None<EOL>newOther = None<EOL>for dim in dims:<EOL><INDENT>sd = self.get(dim, None)<EOL>od = other.get(dim, None)<EOL>if sd is None or od is None:<EOL><INDENT>continue<EOL><DEDENT>if -_EPSILON < sd < _EPSILON and -_EP...
Return two objects with the same dimensions if they lie in the same orthogonal plane. :: >>> l = Location(pop=1, snap=2) >>> m = Location(crackle=1, snap=3) >>> l.common(m) (<Location snap:2 >, <Location snap:3 >)
f11945:c0:m12
def isOrigin(self):
for name, value in self.items():<EOL><INDENT>if isinstance(value, tuple):<EOL><INDENT>if (value < (-_EPSILON,) * len(value)<EOL>or value > (_EPSILON,) * len(value)):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>if value < -_EPSILON or value > _EPSILON:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
Return True if the location is at the origin. :: >>> l = Location(pop=1) >>> l.isOrigin() False >>> l = Location() >>> l.isOrigin() True
f11945:c0:m13
def isOnAxis(self):
new = self.__class__()<EOL>new.update(self)<EOL>s = new.strip()<EOL>dims = list(s.keys())<EOL>if len(dims)> <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>elif len(dims)==<NUM_LIT:1>:<EOL><INDENT>return dims[<NUM_LIT:0>]<EOL><DEDENT>return None<EOL>
Returns statements about this location: * False if the location is not on-axis * The name of the axis if it is on-axis * None if the Location is at the origin Note: this is only valid for an unbiased location. :: >>> l = Location(pop=1) >>> l.isOnAxis() 'pop' >>> l = Location(pop=1,...
f11945:c0:m14
def isAmbivalent(self, dim=None):
if dim is not None:<EOL><INDENT>try:<EOL><INDENT>return isinstance(self[dim], tuple)<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>for dim, val in self.items():<EOL><INDENT>if isinstance(val, tuple):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
Return True if any of the factors are in fact tuples. If a dimension name is given only that dimension is tested. :: >>> l = Location(pop=1) >>> l.isAmbivalent() False >>> l = Location(pop=1, snap=(100, -100)) >>> l.isAmbivalent() True
f11945:c0:m15
def split(self):
x = self.__class__()<EOL>y = self.__class__()<EOL>for dim, val in self.items():<EOL><INDENT>if isinstance(val, tuple):<EOL><INDENT>x[dim] = val[<NUM_LIT:0>]<EOL>y[dim] = val[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>x[dim] = val<EOL>y[dim] = val<EOL><DEDENT><DEDENT>return x, y<EOL>
Split an ambivalent location into 2. One for the x, the other for the y. :: >>> l = Location(pop=(-5,5)) >>> l.split() (<Location pop:-5 >, <Location pop:5 >)
f11945:c0:m16
def spliceX(self):
new = self.__class__()<EOL>for dim, val in self.items():<EOL><INDENT>if isinstance(val, tuple):<EOL><INDENT>new[dim] = val[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>new[dim] = val<EOL><DEDENT><DEDENT>return new<EOL>
Return a copy with the x values preferred for ambivalent locations. :: >>> l = Location(pop=(-5,5)) >>> l.spliceX() <Location pop:-5 >
f11945:c0:m17
def spliceY(self):
new = self.__class__()<EOL>for dim, val in self.items():<EOL><INDENT>if isinstance(val, tuple):<EOL><INDENT>new[dim] = val[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>new[dim] = val<EOL><DEDENT><DEDENT>return new<EOL>
Return a copy with the y values preferred for ambivalent locations. :: >>> l = Location(pop=(-5,5)) >>> l.spliceY() <Location pop:5 >
f11945:c0:m18
def distance(self, other=None):
t = <NUM_LIT:0><EOL>if other is None:<EOL><INDENT>other = self.__class__()<EOL><DEDENT>for axisName in set(self.keys()) | set(other.keys()):<EOL><INDENT>t += (other.get(axisName,<NUM_LIT:0>)-self.get(axisName,<NUM_LIT:0>))**<NUM_LIT:2><EOL><DEDENT>return math.sqrt(t)<EOL>
Return the geometric distance to the other location. If no object is provided, this will calculate the distance to the origin. :: >>> l = Location(pop=100) >>> m = Location(pop=200) >>> l.distance(m) 100.0 >>> l = Location() >>> m...
f11945:c0:m19
def sameAs(self, other):
if not hasattr(other, "<STR_LIT>"):<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>d = self.distance(other)<EOL>if d < _EPSILON:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return -<NUM_LIT:1><EOL>
Check if this is the same location. :: >>> l = Location(pop=5, snap=100) >>> m = Location(pop=5.0, snap=100.0) >>> l.sameAs(m) 0 >>> l = Location(pop=5, snap=100) >>> m = Location(pop=5.0, snap=100.0001) >>> l.sameAs(m) -1
f11945:c0:m20
def regressionTests():
Test all the basic math operations >>> assert Location(a=1) + Location(a=2) == Location(a=3) # addition >>> assert Location(a=1.0) - Location(a=2.0) == Location(a=-1.0) # subtraction >>> assert Location(a=1.0) * 2 == Location(a=2.0) # multiplication >>> assert Location(a=...
f11949:m12
def makeTestFonts(rootPath):
path1 = os.path.join(rootPath, "<STR_LIT>")<EOL>path2 = os.path.join(rootPath, "<STR_LIT>")<EOL>path3 = os.path.join(rootPath, "<STR_LIT>")<EOL>f1 = Font()<EOL>f1.groups['<STR_LIT>'] = ['<STR_LIT>', '<STR_LIT>']<EOL>f1.groups['<STR_LIT>'] = ['<STR_LIT>', '<STR_LIT>']<EOL>addGlyphs(f1)<EOL>f2 = Font()<EOL>f2.groups.upda...
Make some test fonts that have the kerning problem.
f11952:m1
def makeTestFonts(rootPath):
path1 = os.path.join(rootPath, "<STR_LIT>")<EOL>path2 = os.path.join(rootPath, "<STR_LIT>")<EOL>path3 = os.path.join(rootPath, "<STR_LIT>")<EOL>path4 = os.path.join(rootPath, "<STR_LIT>")<EOL>path5 = os.path.join(rootPath, "<STR_LIT>")<EOL>f1 = Font()<EOL>addGlyphs(f1, <NUM_LIT:100>)<EOL>f2 = Font()<EOL>addGlyphs(f2, <...
Make some test fonts that have the kerning problem.
f11953:m3
def bender_and_mutatorTest():
>>> from mutatorMath.objects.bender import Bender >>> from mutatorMath.objects.location import Location >>> from mutatorMath.objects.mutator import buildMutator >>> w = {'aaaa':{ ... 'map': [(300, 50), ... (400, 100), ... (700, 150)], ... 'name':'aaaaAxis', ... 'tag':'aaaa', ... 'mini...
f11954:m2
def makeTestFonts(rootPath):
path1 = os.path.join(rootPath, "<STR_LIT>")<EOL>path2 = os.path.join(rootPath, "<STR_LIT>")<EOL>path3 = os.path.join(rootPath, "<STR_LIT>")<EOL>f1 = Font()<EOL>addGlyphs(f1, <NUM_LIT:0>)<EOL>f1.info.unitsPerEm = <NUM_LIT:1000><EOL>f1.kerning[('<STR_LIT>', '<STR_LIT>')] = -<NUM_LIT:100><EOL>f2 = Font()<EOL>addGlyphs(f2,...
Make some test fonts that have the kerning problem.
f11959:m2
def save(self, pretty=True):
self.endInstance()<EOL>if pretty:<EOL><INDENT>_indent(self.root, whitespace=self._whiteSpace)<EOL><DEDENT>tree = ET.ElementTree(self.root)<EOL>tree.write(self.path, encoding="<STR_LIT:utf-8>", method='<STR_LIT>', xml_declaration=True)<EOL>if self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>", self.path)<EOL><DEDENT>
Save the xml. Make pretty if necessary.
f11961:c0:m1
def _makeLocationElement(self, locationObject, name=None):
locElement = ET.Element("<STR_LIT:location>")<EOL>if name is not None:<EOL><INDENT>locElement.attrib['<STR_LIT:name>'] = name<EOL><DEDENT>for dimensionName, dimensionValue in locationObject.items():<EOL><INDENT>dimElement = ET.Element('<STR_LIT>')<EOL>dimElement.attrib['<STR_LIT:name>'] = dimensionName<EOL>if type(dime...
Convert Location object to an locationElement.
f11961:c0:m2
def addSource(self,<EOL>path,<EOL>name,<EOL>location,<EOL>copyLib=False,<EOL>copyGroups=False,<EOL>copyInfo=False,<EOL>copyFeatures=False,<EOL>muteKerning=False,<EOL>muteInfo=False,<EOL>mutedGlyphNames=None,<EOL>familyName=None,<EOL>styleName=None,<EOL>):
sourceElement = ET.Element("<STR_LIT:source>")<EOL>sourceElement.attrib['<STR_LIT:filename>'] = self._posixPathRelativeToDocument(path)<EOL>sourceElement.attrib['<STR_LIT:name>'] = name<EOL>if copyLib:<EOL><INDENT>libElement = ET.Element('<STR_LIT>')<EOL>libElement.attrib['<STR_LIT>'] = "<STR_LIT:1>"<EOL>sourceElement....
Add a new UFO source to the document. * path: path to this UFO, will be written as a relative path to the document path. * name: reference name for this source * location: name of the location for this UFO * copyLib: copy the contents of this source to instances * copyGroups: ...
f11961:c0:m4
def startInstance(self, name=None,<EOL>location=None,<EOL>familyName=None,<EOL>styleName=None,<EOL>fileName=None,<EOL>postScriptFontName=None,<EOL>styleMapFamilyName=None,<EOL>styleMapStyleName=None,<EOL>):
if self.currentInstance is not None:<EOL><INDENT>self.endInstance()<EOL><DEDENT>instanceElement = ET.Element('<STR_LIT>')<EOL>if name is not None:<EOL><INDENT>instanceElement.attrib['<STR_LIT:name>'] = name<EOL><DEDENT>if location is not None:<EOL><INDENT>locationElement = self._makeLocationElement(location)<EOL>instan...
Start a new instance. Instances can need a lot of configuration. So this method starts a new instance element. Use endInstance() to finish it. * name: the name of this instance * familyName: name for the font.info.familyName field. Required. * styleName...
f11961:c0:m5
def endInstance(self):
if self.currentInstance is None:<EOL><INDENT>return<EOL><DEDENT>allInstances = self.root.findall('<STR_LIT>')[<NUM_LIT:0>].append(self.currentInstance)<EOL>self.currentInstance = None<EOL>
Finalise the instance definition started by startInstance().
f11961:c0:m6
def writeGlyph(self,<EOL>name,<EOL>unicodes=None,<EOL>location=None,<EOL>masters=None,<EOL>note=None,<EOL>mute=False,<EOL>):
if self.currentInstance is None:<EOL><INDENT>return<EOL><DEDENT>glyphElement = ET.Element('<STR_LIT>')<EOL>if mute:<EOL><INDENT>glyphElement.attrib['<STR_LIT>'] = "<STR_LIT:1>"<EOL><DEDENT>if unicodes is not None:<EOL><INDENT>glyphElement.attrib['<STR_LIT>'] = "<STR_LIT:U+0020>".join([hex(u) for u in unicodes])<EOL><DE...
Add a new glyph to the current instance. * name: the glyph name. Required. * unicodes: unicode values for this glyph if it needs to be different from the unicode values associated with this glyph name in the masters. * location: a design space location for this glyph if it needs to b...
f11961:c0:m7
def writeInfo(self, location=None, masters=None):
if self.currentInstance is None:<EOL><INDENT>return<EOL><DEDENT>infoElement = ET.Element("<STR_LIT:info>")<EOL>if location is not None:<EOL><INDENT>locationElement = self._makeLocationElement(location)<EOL>infoElement.append(locationElement)<EOL><DEDENT>self.currentInstance.append(infoElement)<EOL>
Write font into the current instance. Note: the masters attribute is ignored at the moment.
f11961:c0:m8
def writeKerning(self, location=None, masters=None):
if self.currentInstance is None:<EOL><INDENT>return<EOL><DEDENT>kerningElement = ET.Element("<STR_LIT>")<EOL>if location is not None:<EOL><INDENT>locationElement = self._makeLocationElement(location)<EOL>kerningElement.append(locationElement)<EOL><DEDENT>self.currentInstance.append(kerningElement)<EOL>
Write kerning into the current instance. Note: the masters attribute is ignored at the moment.
f11961:c0:m9
def writeWarp(self, warpDict):
warpElement = ET.Element("<STR_LIT>")<EOL>axisNames = sorted(warpDict.keys())<EOL>for name in axisNames:<EOL><INDENT>axisElement = ET.Element("<STR_LIT>")<EOL>axisElement.attrib['<STR_LIT:name>'] = name<EOL>for a, b in warpDict[name]:<EOL><INDENT>warpPt = ET.Element("<STR_LIT>")<EOL>warpPt.attrib['<STR_LIT:input>'] = s...
Write a list of (in, out) values for a warpmap
f11961:c0:m10
def addAxis(self, tag, name, minimum, maximum, default, warpMap=None):
axisElement = ET.Element("<STR_LIT>")<EOL>axisElement.attrib['<STR_LIT:name>'] = name<EOL>axisElement.attrib['<STR_LIT>'] = tag<EOL>axisElement.attrib['<STR_LIT>'] = str(minimum)<EOL>axisElement.attrib['<STR_LIT>'] = str(maximum)<EOL>axisElement.attrib['<STR_LIT:default>'] = str(default)<EOL>if warpMap is not None:<EOL...
Write an axis element. This will be added to the <axes> element.
f11961:c0:m11
def reportProgress(self, state, action, text=None, tick=None):
if self.progressFunc is not None:<EOL><INDENT>self.progressFunc(state=state, action=action, text=text, tick=tick)<EOL><DEDENT>
If we want to keep other code updated about our progress. state: 'prep' reading sources 'generate' making instances 'done' wrapping up 'error' reporting a problem action: 'start' begin generatin...
f11961:c1:m1
def getSourcePaths(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
paths = []<EOL>for name in self.sources.keys():<EOL><INDENT>paths.append(self.sources[name][<NUM_LIT:0>].path)<EOL><DEDENT>return paths<EOL>
Return a list of paths referenced in the document.
f11961:c1:m2
def process(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
if self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>", self.path)<EOL><DEDENT>self.readInstances(makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo)<EOL>self.reportProgress("<STR_LIT>", '<STR_LIT>')<EOL>
Process the input file and generate the instances.
f11961:c1:m3
def readVersion(self):
ds = self.root.findall("<STR_LIT>")[<NUM_LIT:0>]<EOL>raw_format = ds.attrib['<STR_LIT>']<EOL>try:<EOL><INDENT>self.documentFormatVersion = int(raw_format)<EOL><DEDENT>except ValueError:<EOL><INDENT>self.documentFormatVersion = float(raw_format)<EOL><DEDENT>
Read the document version. :: <designspace format="3">
f11961:c1:m4
def readWarp(self):
warpDict = {}<EOL>for warpAxisElement in self.root.findall("<STR_LIT>"):<EOL><INDENT>axisName = warpAxisElement.attrib.get("<STR_LIT:name>")<EOL>warpDict[axisName] = []<EOL>for warpPoint in warpAxisElement.findall("<STR_LIT>"):<EOL><INDENT>inputValue = float(warpPoint.attrib.get("<STR_LIT:input>"))<EOL>outputValue = fl...
Read the warp element :: <warp> <axis name="weight"> <map input="0" output="0" /> <map input="500" output="200" /> <map input="1000" output="1000" /> </axis> </warp>
f11961:c1:m5
def readAxes(self):
for axisElement in self.root.findall("<STR_LIT>"):<EOL><INDENT>axis = {}<EOL>axis['<STR_LIT:name>'] = name = axisElement.attrib.get("<STR_LIT:name>")<EOL>axis['<STR_LIT>'] = axisElement.attrib.get("<STR_LIT>")<EOL>axis['<STR_LIT>'] = float(axisElement.attrib.get("<STR_LIT>"))<EOL>axis['<STR_LIT>'] = float(axisElement.a...
Read the axes element.
f11961:c1:m6
def readSources(self):
for sourceCount, sourceElement in enumerate(self.root.findall("<STR_LIT>")):<EOL><INDENT>filename = sourceElement.attrib.get('<STR_LIT:filename>')<EOL>sourcePath = os.path.abspath(os.path.join(os.path.dirname(self.path), filename))<EOL>sourceName = sourceElement.attrib.get('<STR_LIT:name>')<EOL>if sourceName is None:<E...
Read the source elements. :: <source filename="LightCondensed.ufo" location="location-token-aaa" name="master-token-aaa1"> <info mute="1" copy="1"/> <kerning mute="1"/> <glyph mute="1" name="thirdGlyph"/> </source>
f11961:c1:m7
def locationFromElement(self, element):
elementLocation = None<EOL>for locationElement in element.findall('<STR_LIT>'):<EOL><INDENT>elementLocation = self.readLocationElement(locationElement)<EOL>break<EOL><DEDENT>return elementLocation<EOL>
Find the MutatorMath location of this element, either by name or from a child element.
f11961:c1:m8
def readLocationElement(self, locationElement):
loc = Location()<EOL>for dimensionElement in locationElement.findall("<STR_LIT>"):<EOL><INDENT>dimName = dimensionElement.attrib.get("<STR_LIT:name>")<EOL>xValue = yValue = None<EOL>try:<EOL><INDENT>xValue = dimensionElement.attrib.get('<STR_LIT>')<EOL>xValue = float(xValue)<EOL><DEDENT>except ValueError:<EOL><INDENT>i...
Format 0 location reader
f11961:c1:m9
def readInstance(self, key, makeGlyphs=True, makeKerning=True, makeInfo=True):
attrib, value = key<EOL>for instanceElement in self.root.findall('<STR_LIT>'):<EOL><INDENT>if instanceElement.attrib.get(attrib) == value:<EOL><INDENT>self._readSingleInstanceElement(instanceElement, makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo)<EOL>return<EOL><DEDENT><DEDENT>raise MutatorError("<S...
Read a single instance element. key: an (attribute, value) tuple used to find the requested instance. :: <instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular">
f11961:c1:m10
def readInstances(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
for instanceElement in self.root.findall('<STR_LIT>'):<EOL><INDENT>self._readSingleInstanceElement(instanceElement, makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo)<EOL><DEDENT>
Read all instance elements. :: <instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular">
f11961:c1:m11
def _readSingleInstanceElement(self, instanceElement, makeGlyphs=True, makeKerning=True, makeInfo=True):
<EOL>filename = instanceElement.attrib.get('<STR_LIT:filename>')<EOL>instancePath = os.path.join(os.path.dirname(self.path), filename)<EOL>self.reportProgress("<STR_LIT>", '<STR_LIT:start>', instancePath)<EOL>if self.verbose and self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>", os.path.basename(instancePath))<EOL>...
Read a single instance element. If we have glyph specifications, only make those. Otherwise make all available glyphs.
f11961:c1:m12
def readInfoElement(self, infoElement, instanceObject):
infoLocation = self.locationFromElement(infoElement)<EOL>instanceObject.addInfo(infoLocation, copySourceName=self.infoSource)<EOL>
Read the info element. :: <info/> <info"> <location/> </info>
f11961:c1:m13
def readKerningElement(self, kerningElement, instanceObject):
kerningLocation = self.locationFromElement(kerningElement)<EOL>instanceObject.addKerning(kerningLocation)<EOL>
Read the kerning element. :: Make kerning at the location and with the masters specified at the instance level. <kerning/>
f11961:c1:m14
def readGlyphElement(self, glyphElement, instanceObject):
<EOL>glyphName = glyphElement.attrib.get('<STR_LIT:name>')<EOL>if glyphName is None:<EOL><INDENT>raise MutatorError("<STR_LIT>")<EOL><DEDENT>mute = glyphElement.attrib.get("<STR_LIT>")<EOL>if mute == "<STR_LIT:1>":<EOL><INDENT>instanceObject.muteGlyph(glyphName)<EOL>return<EOL><DEDENT>unicodes = glyphElement.attrib.get...
Read the glyph element. :: <glyph name="b" unicode="0x62"/> <glyph name="b"/> <glyph name="b"> <master location="location-token-bbb" source="master-token-aaa2"/> <master glyphname="b.alt1" location="location-token-ccc" source="master-token-aaa3"/> <note> This is an i...
f11961:c1:m15
def _instantiateFont(self, path):
return self._fontClass(path,<EOL>libClass=self._libClass,<EOL>kerningClass=self._kerningClass,<EOL>groupsClass=self._groupsClass,<EOL>infoClass=self._infoClass,<EOL>featuresClass=self._featuresClass,<EOL>glyphClass=self._glyphClass,<EOL>glyphContourClass=self._glyphContourClass,<EOL>glyphPointClass=self._glyphPointClas...
Return a instance of a font object with all the given subclasses
f11961:c1:m16
def tokenProgressFunc(state="<STR_LIT>", action=None, text=None, tick=<NUM_LIT:0>):
print("<STR_LIT>"%(state, str(action), str(text), str(tick)))<EOL>
state: string, "update", "reading sources", "wrapping up" action: string, "stop", "start" text: string, value, additional parameter. For instance ufoname. tick: a float between 0 and 1 indicating progress.
f11962:m0
def build(<EOL>documentPath,<EOL>outputUFOFormatVersion=<NUM_LIT:2>,<EOL>roundGeometry=True,<EOL>verbose=True,<EOL>logPath=None,<EOL>progressFunc=None,<EOL>):
from mutatorMath.ufo.document import DesignSpaceDocumentReader<EOL>import os, glob<EOL>if os.path.isdir(documentPath):<EOL><INDENT>todo = glob.glob(os.path.join(documentPath, "<STR_LIT>"))<EOL><DEDENT>else:<EOL><INDENT>todo = [documentPath]<EOL><DEDENT>results = []<EOL>for path in todo:<EOL><INDENT>reader = DesignSpace...
Simple builder for UFO designspaces.
f11962:m1
def setSources(self, sources):
self.sources = sources<EOL>
Set a list of sources.
f11963:c0:m1
def setMuted(self, muted):
self.muted.update(muted)<EOL>
Set the mute states.
f11963:c0:m2
def muteGlyph(self, glyphName):
self.mutedGlyphsNames.append(glyphName)<EOL>
Mute the generating of this specific glyph.
f11963:c0:m3
def setGroups(self, groups, kerningGroupConversionRenameMaps=None):
skipping = []<EOL>for name, members in groups.items():<EOL><INDENT>checked = []<EOL>for m in members:<EOL><INDENT>if m in self.font:<EOL><INDENT>checked.append(m)<EOL><DEDENT>else:<EOL><INDENT>skipping.append(m)<EOL><DEDENT><DEDENT>if checked:<EOL><INDENT>self.font.groups[name] = checked<EOL><DEDENT><DEDENT>if skipping...
Copy the groups into our font.
f11963:c0:m4
def getFailed(self):
return self._failed<EOL>
Return the list of glyphnames that failed to generate.
f11963:c0:m5
def getMissingUnicodes(self):
return self._missingUnicodes<EOL>
Return the list of glyphnames with missing unicode values.
f11963:c0:m6
def setLib(self, lib):
for name, item in lib.items():<EOL><INDENT>self.font.lib[name] = item<EOL><DEDENT>
Copy the lib items into our font.
f11963:c0:m7
def setPostScriptFontName(self, name):
self.font.info.postscriptFontName = name<EOL>
Set the postScriptFontName.
f11963:c0:m8
def setStyleMapFamilyName(self, name):
self.font.info.styleMapFamilyName = name<EOL>
Set the stylemap FamilyName.
f11963:c0:m9
def setStyleMapStyleName(self, name):
self.font.info.styleMapStyleName = name<EOL>
Set the stylemap StyleName.
f11963:c0:m10
def setStyleName(self, name):
self.font.info.styleName = name<EOL>
Set the styleName.
f11963:c0:m11
def setFamilyName(self, name):
self.font.info.familyName = name<EOL>
Set the familyName
f11963:c0:m12
def copyFeatures(self, featureSource):
if featureSource in self.sources:<EOL><INDENT>src, loc = self.sources[featureSource]<EOL>if isinstance(src.features.text, str):<EOL><INDENT>self.font.features.text = u"<STR_LIT>"+src.features.text<EOL><DEDENT>elif isinstance(src.features.text, unicode):<EOL><INDENT>self.font.features.text = src.features.text<EOL><DEDEN...
Copy the features from this source
f11963:c0:m13
def makeUnicodeMapFromSources(self):
values = {}<EOL>for locationName, (source, loc) in self.sources.items():<EOL><INDENT>for glyph in source:<EOL><INDENT>if glyph.unicodes is not None:<EOL><INDENT>if glyph.name not in values:<EOL><INDENT>values[glyph.name] = {}<EOL><DEDENT><DEDENT>for u in glyph.unicodes:<EOL><INDENT>values[glyph.name][u] = <NUM_LIT:1><E...
Create a dict with glyphName -> unicode value pairs using the data in the sources. If all master glyphs have the same unicode value this value will be used in the map. If master glyphs have conflicting value, a warning will be printed, no value will be used. ...
f11963:c0:m14
def getAvailableGlyphnames(self):
glyphNames = {}<EOL>for locationName, (source, loc) in self.sources.items():<EOL><INDENT>for glyph in source:<EOL><INDENT>glyphNames[glyph.name] = <NUM_LIT:1><EOL><DEDENT><DEDENT>names = sorted(glyphNames.keys())<EOL>return names<EOL>
Return a list of all glyphnames we have masters for.
f11963:c0:m15
def setLocation(self, locationObject):
self.locationObject = locationObject<EOL>
Set the location directly.
f11963:c0:m16
def addInfo(self, instanceLocation=None, sources=None, copySourceName=None):
if instanceLocation is None:<EOL><INDENT>instanceLocation = self.locationObject<EOL><DEDENT>infoObject = self.font.info<EOL>infoMasters = []<EOL>if sources is None:<EOL><INDENT>sources = self.sources<EOL><DEDENT>items = []<EOL>for sourceName, (source, sourceLocation) in sources.items():<EOL><INDENT>if sourceName in sel...
Add font info data.
f11963:c0:m17
def _copyFontInfo(self, targetInfo, sourceInfo):
infoAttributes = [<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LI...
Copy the non-calculating fields from the source info.
f11963:c0:m18
def addKerning(self, instanceLocation=None, sources=None):
items = []<EOL>kerningObject = self.font.kerning<EOL>kerningMasters = []<EOL>if instanceLocation is None:<EOL><INDENT>instanceLocation = self.locationObject<EOL><DEDENT>if sources is None:<EOL><INDENT>sources = self.sources<EOL><DEDENT>for sourceName, (source, sourceLocation) in sources.items():<EOL><INDENT>if sourceNa...
Calculate the kerning data for this location and add it to this instance. * instanceLocation: Location object * source: dict of {sourcename: (source, sourceLocation)}
f11963:c0:m19
def addGlyph(self, glyphName, unicodes=None, instanceLocation=None, sources=None, note=None):
self.font.newGlyph(glyphName)<EOL>glyphObject = self.font[glyphName]<EOL>if note is not None:<EOL><INDENT>glyphObject.note = note<EOL><DEDENT>if unicodes is not None:<EOL><INDENT>glyphObject.unicodes = unicodes<EOL><DEDENT>if instanceLocation is None:<EOL><INDENT>instanceLocation = self.locationObject<EOL><DEDENT>glyph...
Calculate a new glyph and add it to this instance. * glyphName: The name of the glyph * unicodes: The unicode values for this glyph (optional) * instanceLocation: Location for this glyph * sources: List of sources for this glyph. * note: Note for this glyph.
f11963:c0:m20
def _calculateGlyph(self, targetGlyphObject, instanceLocationObject, glyphMasters):
sources = None<EOL>items = []<EOL>for item in glyphMasters:<EOL><INDENT>locationObject = item['<STR_LIT:location>']<EOL>fontObject = item['<STR_LIT>']<EOL>glyphName = item['<STR_LIT>']<EOL>if not glyphName in fontObject:<EOL><INDENT>continue<EOL><DEDENT>glyphObject = MathGlyph(fontObject[glyphName])<EOL>items.append((l...
Build a Mutator object for this glyph. * name: glyphName * location: Location object * glyphMasters: dict with font objects.
f11963:c0:m21
def save(self):
<EOL>for name in self.mutedGlyphsNames:<EOL><INDENT>if name not in self.font: continue<EOL>if self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>", name)<EOL><DEDENT>del self.font[name]<EOL><DEDENT>directory = os.path.dirname(os.path.normpath(self.path))<EOL>if directory and not os.path.exists(directory):<EOL><INDENT>...
Save the UFO.
f11963:c0:m22
def render(value):
<EOL>if not value: <EOL><INDENT>return r'<STR_LIT>'<EOL><DEDENT>if value[<NUM_LIT:0>] != beginning:<EOL><INDENT>value = beginning + value<EOL><DEDENT>if value[-<NUM_LIT:1>] != end:<EOL><INDENT>value += end<EOL><DEDENT>return value<EOL>
This function finishes the url pattern creation by adding starting character ^ end possibly by adding end character at the end :param value: naive URL value :return: raw string
f11970:m0
def __new__(cls, value='<STR_LIT>', separator=SEPARATOR):
self = str.__new__(cls, render(value))<EOL>self.separator = separator<EOL>return self<EOL>
:param value: Initial value of the URL :param separator: used to separate parts of the url, usually /
f11970:c0:m0
def add_part(self, part):
if isinstance(part, RE_TYPE):<EOL><INDENT>part = part.pattern<EOL><DEDENT>if self == '<STR_LIT>':<EOL><INDENT>return URLPattern(part, self.separator)<EOL><DEDENT>else:<EOL><INDENT>sep = self.separator<EOL>return URLPattern(self.rstrip('<STR_LIT:$>' + sep) + sep + part.lstrip(sep),<EOL>sep)<EOL><DEDENT>
Function for adding partial pattern to the value :param part: string or compiled pattern
f11970:c0:m1
def url_view(url_pattern, name=None, priority=None):
def meta_wrapper(func):<EOL><INDENT>@functools.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>wrapper.urljects_view = True<EOL>wrapper.url = url_pattern<EOL>wrapper.url_name = name or func.__name__<EOL>wrapper.url_priority = priority<EOL>return wrapper<EOL><DEDENT>ret...
Decorator for registering functional views. Meta decorator syntax has to be used in order to accept arguments. This decorator does not really do anything that magical: This: >>> from urljects import U, url_view >>> @url_view(U / 'my_view') ... def my_view(request) ... pass is equivalent to this: >>> def my_view(...
f11971:m0
def resolve_name(view):
if inspect.isfunction(view):<EOL><INDENT>return view.__name__<EOL><DEDENT>if hasattr(view, '<STR_LIT>'):<EOL><INDENT>return view.url_name<EOL><DEDENT>if isinstance(view, six.string_types):<EOL><INDENT>return view.split('<STR_LIT:.>')[-<NUM_LIT:1>]<EOL><DEDENT>return None<EOL>
Auto guesses name of the view. For function it will be ``view.__name__`` For classes it will be ``view.url_name``
f11971:m1
def url(url_pattern, view, kwargs=None, name=None):
<EOL>if isinstance(url_pattern, URLPattern) and isinstance(view, tuple):<EOL><INDENT>url_pattern = url_pattern.for_include()<EOL><DEDENT>if name is None:<EOL><INDENT>name = resolve_name(view)<EOL><DEDENT>if callable(view) and hasattr(view, '<STR_LIT>') and callable(view.as_view):<EOL><INDENT>view = view.as_view()<EOL><...
This is replacement for ``django.conf.urls.url`` function. This url auto calls ``as_view`` method for Class based views and resolves URLPattern objects. If ``name`` is not specified it will try to guess it. :param url_pattern: string with regular expression or URLPattern :param view: function/string/class of the view...
f11971:m2
def view_include(view_module, namespace=None, app_name=None):
<EOL>view_dict = defaultdict(list)<EOL>if isinstance(view_module, six.string_types):<EOL><INDENT>view_module = importlib.import_module(view_module)<EOL><DEDENT>for member_name, member in inspect.getmembers(view_module):<EOL><INDENT>is_class_view = inspect.isclass(member) and issubclass(member, URLView)<EOL>is_func_view...
Includes view in the url, works similar to django include function. Auto imports all class based views that are subclass of ``URLView`` and all functional views that have been decorated with ``url_view``. :param view_module: object of the module or string with importable path :param namespace: name of the namespaces, ...
f11971:m3
def __call__(self, url_pattern, view=None, name=None, priority=<NUM_LIT:0>,<EOL>kwargs=None):
def router_decorator(view):<EOL><INDENT>if name is None:<EOL><INDENT>resolved_name = resolve_name(view)<EOL><DEDENT>else:<EOL><INDENT>resolved_name = name<EOL><DEDENT>url_object = url(url_pattern, view, kwargs=kwargs,<EOL>name=resolved_name)<EOL>self.routes.append((priority, url_object))<EOL>return view<EOL><DEDENT>if ...
Register a URL -> view mapping, or return a registering decorator. :param url_pattern: regex or URLPattern or anything passable to url() :param view: The view. If None, a decorator will be returned The remaining arguments should be given by name: :param name: name of the view; resolve...
f11973:c0:m1
def include(self, location, namespace=None, app_name=None):
sorted_entries = sorted(self.routes, key=operator.itemgetter(<NUM_LIT:0>),<EOL>reverse=True)<EOL>arg = [u for _, u in sorted_entries]<EOL>return url(location, urls.include(<EOL>arg=arg,<EOL>namespace=namespace,<EOL>app_name=app_name))<EOL>
Return an object suitable for url_patterns. :param location: root URL for all URLs from this router :param namespace: passed to url() :param app_name: passed to url()
f11973:c0:m2
def datetime2yeardoy(time: Union[str, datetime.datetime]) -> Tuple[int, float]:
T = np.atleast_1d(time)<EOL>utsec = np.empty_like(T, float)<EOL>yd = np.empty_like(T, int)<EOL>for i, t in enumerate(T):<EOL><INDENT>if isinstance(t, np.datetime64):<EOL><INDENT>t = t.astype(datetime.datetime)<EOL><DEDENT>elif isinstance(t, str):<EOL><INDENT>t = parse(t)<EOL><DEDENT>utsec[i] = datetime2utsec(t)<EOL>yd[...
Inputs: T: Numpy 1-D array of datetime.datetime OR string for dateutil.parser.parse Outputs: yd: yyyyddd four digit year, 3 digit day of year (INTEGER) utsec: seconds from midnight utc
f11980:m0
def yeardoy2datetime(yeardate: int,<EOL>utsec: Union[float, int] = None) -> datetime.datetime:
if isinstance(yeardate, (tuple, list, np.ndarray)):<EOL><INDENT>if utsec is None:<EOL><INDENT>return np.asarray([yeardoy2datetime(y) for y in yeardate])<EOL><DEDENT>elif isinstance(utsec, (tuple, list, np.ndarray)):<EOL><INDENT>return np.asarray([yeardoy2datetime(y, s) for y, s in zip(yeardate, utsec)])<EOL><DEDENT><DE...
Inputs: yd: yyyyddd four digit year, 3 digit day of year (INTEGER 7 digits) outputs: t: datetime http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date
f11980:m1
def date2doy(time: Union[str, datetime.datetime]) -> Tuple[int, int]:
T = np.atleast_1d(time)<EOL>year = np.empty(T.size, dtype=int)<EOL>doy = np.empty_like(year)<EOL>for i, t in enumerate(T):<EOL><INDENT>yd = str(datetime2yeardoy(t)[<NUM_LIT:0>])<EOL>year[i] = int(yd[:<NUM_LIT:4>])<EOL>doy[i] = int(yd[<NUM_LIT:4>:])<EOL><DEDENT>assert ((<NUM_LIT:0> < doy) & (doy < <NUM_LIT>)).all(), '<S...
< 366 for leap year too. normal year 0..364. Leap 0..365.
f11980:m2
def datetime2gtd(time: Union[str, datetime.datetime, np.datetime64],<EOL>glon: Union[float, List[float], np.ndarray] = np.nan) -> Tuple[int, float, float]:
<EOL><INDENT>T = np.atleast_1d(time)<EOL>glon = np.asarray(glon)<EOL>doy = np.empty_like(T, int)<EOL>utsec = np.empty_like(T, float)<EOL>stl = np.empty((T.size, *glon.shape))<EOL>for i, t in enumerate(T):<EOL><INDENT>if isinstance(t, str):<EOL><INDENT>t = parse(t)<EOL><DEDENT>elif isinstance(t, np.datetime64):<EOL><IND...
Inputs: time: Numpy 1-D array of datetime.datetime OR string for dateutil.parser.parse glon: Numpy 2-D array of geodetic longitudes (degrees) Outputs: iyd: day of year utsec: seconds from midnight utc stl: local solar time
f11980:m3
def datetime2utsec(t: Union[str, datetime.date, datetime.datetime, np.datetime64]) -> float:
if isinstance(t, (tuple, list, np.ndarray)):<EOL><INDENT>return np.asarray([datetime2utsec(T) for T in t])<EOL><DEDENT>elif isinstance(t, datetime.date) and not isinstance(t, datetime.datetime):<EOL><INDENT>return <NUM_LIT:0.><EOL><DEDENT>elif isinstance(t, np.datetime64):<EOL><INDENT>t = t.astype(datetime.datetime)<EO...
input: datetime output: float utc seconds since THIS DAY'S MIDNIGHT
f11980:m4
def yeardec2datetime(atime: float) -> datetime.datetime:
<EOL><INDENT>if isinstance(atime, (float, int)): <EOL><INDENT>year = int(atime)<EOL>remainder = atime - year<EOL>boy = datetime.datetime(year, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>eoy = datetime.datetime(year + <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>seconds = remainder * (eoy - boy).total_seconds()<EOL>T = boy + datetime...
Convert atime (a float) to DT.datetime This is the inverse of datetime2yeardec. assert dt2t(t2dt(atime)) == atime http://stackoverflow.com/questions/19305991/convert-fractional-years-to-a-real-date-in-python Authored by "unutbu" http://stackoverflow.com/users/190597/unutbu In Python, go from decimal year (YYYY.YYY) t...
f11980:m5
def datetime2yeardec(time: Union[str, datetime.datetime, datetime.date]) -> float:
if isinstance(time, str):<EOL><INDENT>t = parse(time)<EOL><DEDENT>elif isinstance(time, datetime.datetime):<EOL><INDENT>t = time<EOL><DEDENT>elif isinstance(time, datetime.date):<EOL><INDENT>t = datetime.datetime.combine(time, datetime.datetime.min.time())<EOL><DEDENT>elif isinstance(time, (tuple, list, np.ndarray)):<E...
Convert a datetime into a float. The integer part of the float should represent the year. Order should be preserved. If adate<bdate, then d2t(adate)<d2t(bdate) time distances should be preserved: If bdate-adate=ddate-cdate then dt2t(bdate)-dt2t(adate) = dt2t(ddate)-dt2t(cdate)
f11980:m6
def randomdate(year: int) -> datetime.date:
if calendar.isleap(year):<EOL><INDENT>doy = random.randrange(<NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>doy = random.randrange(<NUM_LIT>)<EOL><DEDENT>return datetime.date(year, <NUM_LIT:1>, <NUM_LIT:1>) + datetime.timedelta(days=doy)<EOL>
gives random date in year
f11980:m7
def timeticks(tdiff):
if isinstance(tdiff, xarray.DataArray): <EOL><INDENT>tdiff = timedelta(seconds=tdiff.values / np.timedelta64(<NUM_LIT:1>, '<STR_LIT:s>'))<EOL><DEDENT>assert isinstance(tdiff, timedelta), '<STR_LIT>'<EOL>if tdiff > timedelta(hours=<NUM_LIT:2>):<EOL><INDENT>return None, None<EOL><DEDENT>elif tdiff > timedelta(minutes=<N...
NOTE do NOT use "interval" or ticks are misaligned! use "bysecond" only!
f11981:m1
def forceutc(t: Union[str, datetime.datetime, datetime.date, np.datetime64]) -> Union[datetime.datetime, datetime.date]:
<EOL><INDENT>polymorph to datetime<EOL><DEDENT>if isinstance(t, str):<EOL><INDENT>t = parse(t)<EOL><DEDENT>elif isinstance(t, np.datetime64):<EOL><INDENT>t = t.astype(datetime.datetime)<EOL><DEDENT>elif isinstance(t, datetime.datetime):<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(t, datetime.date):<EOL><INDENT>return ...
Add UTC to datetime-naive and convert to UTC for datetime aware input: python datetime (naive, utc, non-utc) or Numpy datetime64 #FIXME add Pandas and AstroPy time classes output: utc datetime
f11982:m0
def find_nearest(x, x0) -> Tuple[int, Any]:
x = np.asanyarray(x) <EOL>x0 = np.atleast_1d(x0)<EOL>if x.size == <NUM_LIT:0> or x0.size == <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if x0.ndim not in (<NUM_LIT:0>, <NUM_LIT:1>):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>ind = np.empty_like(x0, dtype=int)<EOL>for i, xi in enumerat...
This find_nearest function does NOT assume sorted input inputs: x: array (float, int, datetime, h5py.Dataset) within which to search for x0 x0: singleton or array of values to search for in x outputs: idx: index of flattened x nearest to x0 (i.e. works with higher than 1-D arrays also) xidx: x[idx] Observe how bise...
f11983:m0
def set_params(method, params):
data = {'<STR_LIT>': method, '<STR_LIT>': params, '<STR_LIT:id>': str(uuid4())}<EOL>return json.dumps(data)<EOL>
Set params to query limesurvey
f11987:m0
def get_session_key(limedict):
url = limedict['<STR_LIT:url>']<EOL>user = limedict['<STR_LIT:username>']<EOL>password = limedict['<STR_LIT:password>']<EOL>params = {'<STR_LIT:username>': user, '<STR_LIT:password>': password}<EOL>data = set_params('<STR_LIT>', params)<EOL>req = requests.post(url, data=data, headers=headers)<EOL>return {'<STR_LIT>': r...
This function receive a dictionary with connection parameters. { "url": "full path for remote control", "username: "account name to be used" "password" "password for account"}
f11987:m1
def list_surveys(session):
params = {'<STR_LIT>': session['<STR_LIT:user>'], '<STR_LIT>': session['<STR_LIT>']}<EOL>data = set_params('<STR_LIT>', params)<EOL>req = requests.post(session['<STR_LIT:url>'], data=data, headers=headers)<EOL>return req.text<EOL>
retrieve a list of surveys from current user
f11987:m2
@step<EOL>def help(project, task, step, variables):
task_name = step.args or variables['<STR_LIT>']<EOL>try:<EOL><INDENT>task = project.find_task(task_name)<EOL><DEDENT>except NoSuchTaskError as e:<EOL><INDENT>yield events.task_not_found(task_name, e.similarities)<EOL>raise StopTask<EOL><DEDENT>text = f'<STR_LIT>'<EOL>text += '<STR_LIT:\n>'<EOL>text += task.description<...
Run a help step.
f11992:m3
def parse_variables(args):
if args is None:<EOL><INDENT>return {}<EOL><DEDENT>def parse_variable(string):<EOL><INDENT>tokens = string.split('<STR_LIT:=>')<EOL>name = tokens[<NUM_LIT:0>]<EOL>value = '<STR_LIT:=>'.join(tokens[<NUM_LIT:1>:])<EOL>return name, value<EOL><DEDENT>return {<EOL>name: value<EOL>for name, value in (parse_variable(v) for v ...
Parse variables as passed on the command line. Returns ------- dict Mapping variable name to the value.
f11993:m0
def main():
args = parse_args()<EOL>frontend = available_frontends[args.frontend]()<EOL>frontend.begin()<EOL>try:<EOL><INDENT>for event in run(args):<EOL><INDENT>frontend.output(event)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>frontend.end()<EOL><DEDENT>
Run the CLI.
f11993:m3
def begin(self):
pass<EOL>
Begin processing output.
f11994:c0:m0
def end(self):
pass<EOL>
End processing output.
f11994:c0:m1
def output(self, event):
pass<EOL>
Process a single event.
f11994:c0:m2
def serialise(self, obj):
if isinstance(obj, (list, VariableCollection, StepCollection)):<EOL><INDENT>return [self.serialise(element) for element in obj]<EOL><DEDENT>elif isinstance(obj, dict):<EOL><INDENT>return {k: self.serialise(v) for k, v in obj.items()}<EOL><DEDENT>elif isinstance(obj, str):<EOL><INDENT>return obj<EOL><DEDENT>elif isinsta...
Take an object from the project or the runner and serialise it into a dictionary. Parameters ---------- obj : object An object to serialise. Returns ------- object A serialised version of the input object.
f11994:c3:m0