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 short:<EOL><INDENT>t.append("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>t.append("<STR_LIT>"%onAxis)<EOL><DEDENT><DEDENT>if self.isAmbivalent():<EOL><INDENT>t.append("<STR_LIT>")<EOL><DEDENT>return '<STR_LIT:U+002CU+0020>'.join(t)<EOL> | 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)
>>> l.getType()
'off-axis, pop snap'
>>> l = Location(pop=(1,2))
>>> l.getType()
'on-axis, pop, split' | 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_LIT>"%(value[<NUM_LIT:0>], value[<NUM_LIT:1>])<EOL><DEDENT>elif int(value) == value:<EOL><INDENT>s = "<STR_LIT>"%(int(value))<EOL><DEDENT>else:<EOL><INDENT>s = "<STR_LIT>"%(value)<EOL><DEDENT>if s != '<STR_LIT>':<EOL><INDENT>n.append("<STR_LIT>"%(name, s))<EOL><DEDENT><DEDENT>return "<STR_LIT:U+002CU+0020>".join(n)<EOL><DEDENT>except TypeError:<EOL><INDENT>import traceback<EOL>print("<STR_LIT>", name, value)<EOL>for key, value in self.items():<EOL><INDENT>print("<STR_LIT>", key)<EOL>print("<STR_LIT>", value)<EOL><DEDENT>traceback.print_exc()<EOL>return "<STR_LIT:error>"<EOL><DEDENT> | 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']
'snap'
>>> l.asSortedStringDict()[1]['value']
'(1,10)' | 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__(result)<EOL> | 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 -_EPSILON < od < _EPSILON:<EOL><INDENT>continue<EOL><DEDENT>if newSelf is None:<EOL><INDENT>newSelf = self.__class__()<EOL><DEDENT>if newOther is None:<EOL><INDENT>newOther = self.__class__()<EOL><DEDENT>newSelf[dim] = self[dim]<EOL>newOther[dim] = other[dim]<EOL><DEDENT>return newSelf, newOther<EOL> | 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, snap=1)
>>> l.isOnAxis()
False
>>> l = Location()
>>> l.isOnAxis() is None
True | 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 = Location(pop=200)
>>> l.distance(m)
200.0
>>> l = Location(pop=3, snap=5)
>>> m = Location(pop=7, snap=8)
>>> l.distance(m)
5.0 | 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=1.0) * 0 == Location(a=0.0) # multiplication
>>> assert Location(a=2.0) / 2 == Location(a=1.0) # division
>>> assert Location(a=(1,2)) * 2 == Location(a=(2,4)) # multiplication with ambivalence
>>> assert Location(a=(2,4)) / 2 == Location(a=(1,2)) # division with ambivalence
>>> assert Location(a=(2,4)) - Location(a=1) == Location(a=(1,3)) | 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.update(f1.groups)<EOL>addGlyphs(f2)<EOL>assert f1.groups == f2.groups<EOL>f1.kerning[('<STR_LIT>', '<STR_LIT>')] = <NUM_LIT:1000><EOL>f1.kerning[('<STR_LIT:a>', '<STR_LIT:b>')] = <NUM_LIT:10><EOL>f2.kerning[('<STR_LIT>', '<STR_LIT>')] = <NUM_LIT><EOL>f2.kerning[('<STR_LIT:a>', '<STR_LIT:b>')] = <NUM_LIT:10><EOL>f1.kerning[('<STR_LIT>', '<STR_LIT>')] = -<NUM_LIT><EOL>f2.kerning[('<STR_LIT>', '<STR_LIT>')] = -<NUM_LIT><EOL>f1.save(path1, <NUM_LIT:3>)<EOL>f2.save(path2, <NUM_LIT:3>)<EOL>return path1, path2, path3<EOL> | 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, <NUM_LIT>)<EOL>fillInfo(f1)<EOL>fillInfo(f2)<EOL>f1.save(path1, <NUM_LIT:2>)<EOL>f2.save(path2, <NUM_LIT:2>)<EOL>return path1, path2, path3, path4, path5<EOL> | 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',
... 'minimum':0,
... 'maximum':1000,
... 'default':0}}
>>> b = Bender(w)
>>> assert b(dict(aaaa=300)) == {'aaaa': 50}
>>> assert b(dict(aaaa=400)) == {'aaaa': 100}
>>> assert b(dict(aaaa=700)) == {'aaaa': 150}
>>> items = [
... (Location(aaaa=300), 0),
... (Location(aaaa=400), 50),
... (Location(aaaa=700), 100),
... ]
>>> bias, mut = buildMutator(items, w, bias=Location(aaaa=400))
>>> bias
<Location aaaa:100 >
>>> bias, mut = buildMutator(items, w, bias=Location(aaaa=700))
>>> bias
<Location aaaa:150 >
>>> bias, mut = buildMutator(items, w, bias=Location(aaaa=300))
>>> bias
<Location aaaa:50 >
>>> expect = sorted([(('aaaa', 100),), (('aaaa', 50),), ()])
>>> expect
[(), (('aaaa', 50),), (('aaaa', 100),)]
>>> got = sorted(mut.keys())
>>> got
[(), (('aaaa', 50),), (('aaaa', 100),)]
>>> assert got == expect
>>> assert mut.makeInstance(Location(aaaa=300)) == 0
>>> assert mut.makeInstance(Location(aaaa=400)) == 50
>>> assert mut.makeInstance(Location(aaaa=700)) == 100 | 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, <NUM_LIT>)<EOL>f2.info.unitsPerEm = <NUM_LIT><EOL>f2.kerning[('<STR_LIT>', '<STR_LIT>')] = -<NUM_LIT:200><EOL>f1.save(path1, <NUM_LIT:3>)<EOL>f2.save(path2, <NUM_LIT:3>)<EOL>return path1, path2, path3<EOL> | 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(dimensionValue)==tuple:<EOL><INDENT>dimElement.attrib['<STR_LIT>'] = "<STR_LIT>"%dimensionValue[<NUM_LIT:0>]<EOL>dimElement.attrib['<STR_LIT>'] = "<STR_LIT>"%dimensionValue[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>dimElement.attrib['<STR_LIT>'] = "<STR_LIT>"%dimensionValue<EOL><DEDENT>locElement.append(dimElement)<EOL><DEDENT>return locElement<EOL> | 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.append(libElement)<EOL><DEDENT>if copyGroups:<EOL><INDENT>groupsElement = ET.Element('<STR_LIT>')<EOL>groupsElement.attrib['<STR_LIT>'] = "<STR_LIT:1>"<EOL>sourceElement.append(groupsElement)<EOL><DEDENT>if copyFeatures:<EOL><INDENT>featuresElement = ET.Element('<STR_LIT>')<EOL>featuresElement.attrib['<STR_LIT>'] = "<STR_LIT:1>"<EOL>sourceElement.append(featuresElement)<EOL><DEDENT>if copyInfo or muteInfo:<EOL><INDENT>infoElement = ET.Element('<STR_LIT:info>')<EOL>if copyInfo:<EOL><INDENT>infoElement.attrib['<STR_LIT>'] = "<STR_LIT:1>"<EOL><DEDENT>if muteInfo:<EOL><INDENT>infoElement.attrib['<STR_LIT>'] = "<STR_LIT:1>"<EOL><DEDENT>sourceElement.append(infoElement)<EOL><DEDENT>if muteKerning:<EOL><INDENT>kerningElement = ET.Element("<STR_LIT>")<EOL>kerningElement.attrib["<STR_LIT>"] = '<STR_LIT:1>'<EOL>sourceElement.append(kerningElement)<EOL><DEDENT>if mutedGlyphNames:<EOL><INDENT>for name in mutedGlyphNames:<EOL><INDENT>glyphElement = ET.Element("<STR_LIT>")<EOL>glyphElement.attrib["<STR_LIT:name>"] = name<EOL>glyphElement.attrib["<STR_LIT>"] = '<STR_LIT:1>'<EOL>sourceElement.append(glyphElement)<EOL><DEDENT><DEDENT>if familyName is not None:<EOL><INDENT>sourceElement.attrib['<STR_LIT>'] = familyName<EOL><DEDENT>if styleName is not None:<EOL><INDENT>sourceElement.attrib['<STR_LIT>'] = styleName<EOL><DEDENT>locationElement = self._makeLocationElement(location)<EOL>sourceElement.append(locationElement)<EOL>self.root.findall('<STR_LIT>')[<NUM_LIT:0>].append(sourceElement)<EOL> | 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: copy the groups of this source to instances
* copyInfo: copy the non-numerical fields from this source.info to instances.
* copyFeatures: copy the feature text from this source to instances
* muteKerning: mute the kerning data from this source
* muteInfo: mute the font info data from this source
* familyName: family name for this UFO (to be able to work on the names without reading the whole UFO)
* styleName: style name for this UFO (to be able to work on the names without reading the whole UFO)
Note: no separate flag for mute font: the source is just not added. | 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>instanceElement.append(locationElement)<EOL><DEDENT>if familyName is not None:<EOL><INDENT>instanceElement.attrib['<STR_LIT>'] = familyName<EOL><DEDENT>if styleName is not None:<EOL><INDENT>instanceElement.attrib['<STR_LIT>'] = styleName<EOL><DEDENT>if fileName is not None:<EOL><INDENT>instanceElement.attrib['<STR_LIT:filename>'] = self._posixPathRelativeToDocument(fileName)<EOL><DEDENT>if postScriptFontName is not None:<EOL><INDENT>instanceElement.attrib['<STR_LIT>'] = postScriptFontName<EOL><DEDENT>if styleMapFamilyName is not None:<EOL><INDENT>instanceElement.attrib['<STR_LIT>'] = styleMapFamilyName<EOL><DEDENT>if styleMapStyleName is not None:<EOL><INDENT>instanceElement.attrib['<STR_LIT>'] = styleMapStyleName<EOL><DEDENT>self.currentInstance = instanceElement<EOL> | 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: name fot the font.info.styleName field. Required.
* fileName: filename for the instance UFO file. Required.
* postScriptFontName: name for the font.info.postScriptFontName field. Optional.
* styleMapFamilyName: name for the font.info.styleMapFamilyName field. Optional.
* styleMapStyleName: name for the font.info.styleMapStyleName field. Optional. | 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><DEDENT>if location is not None:<EOL><INDENT>locationElement = self._makeLocationElement(location)<EOL>glyphElement.append(locationElement)<EOL><DEDENT>if name is not None:<EOL><INDENT>glyphElement.attrib['<STR_LIT:name>'] = name<EOL><DEDENT>if note is not None:<EOL><INDENT>noteElement = ET.Element('<STR_LIT>')<EOL>noteElement.text = note<EOL>glyphElement.append(noteElement)<EOL><DEDENT>if masters is not None:<EOL><INDENT>mastersElement = ET.Element("<STR_LIT>")<EOL>for glyphName, masterName, location in masters:<EOL><INDENT>masterElement = ET.Element("<STR_LIT>")<EOL>if glyphName is not None:<EOL><INDENT>masterElement.attrib['<STR_LIT>'] = glyphName<EOL><DEDENT>masterElement.attrib['<STR_LIT:source>'] = masterName<EOL>if location is not None:<EOL><INDENT>locationElement = self._makeLocationElement(location)<EOL>masterElement.append(locationElement)<EOL><DEDENT>mastersElement.append(masterElement)<EOL><DEDENT>glyphElement.append(mastersElement)<EOL><DEDENT>if self.currentInstance.findall('<STR_LIT>') == []:<EOL><INDENT>glyphsElement = ET.Element('<STR_LIT>')<EOL>self.currentInstance.append(glyphsElement)<EOL><DEDENT>else:<EOL><INDENT>glyphsElement = self.currentInstance.findall('<STR_LIT>')[<NUM_LIT:0>]<EOL><DEDENT>glyphsElement.append(glyphElement)<EOL> | 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 be different from the instance location.
* masters: a list of masters and locations for this glyph if they need to be different from the masters specified for this instance.
* note: a note for this glyph
* mute: if this glyph is muted. None of the other attributes matter if this one is true. | 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>'] = str(a)<EOL>warpPt.attrib['<STR_LIT>'] = str(b)<EOL>axisElement.append(warpPt)<EOL><DEDENT>warpElement.append(axisElement)<EOL><DEDENT>self.root.append(warpElement)<EOL> | 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><INDENT>for a, b in warpMap:<EOL><INDENT>warpPt = ET.Element("<STR_LIT>")<EOL>warpPt.attrib['<STR_LIT:input>'] = str(a)<EOL>warpPt.attrib['<STR_LIT>'] = str(b)<EOL>axisElement.append(warpPt)<EOL><DEDENT><DEDENT>self.root.findall('<STR_LIT>')[<NUM_LIT:0>].append(axisElement)<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 generating
'stop' end generating
'source' which ufo we're reading
text: <file.ufo> ufoname (for instance)
tick: a float between 0 and 1 indicating progress. | 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 = float(warpPoint.attrib.get("<STR_LIT>"))<EOL>warpDict[axisName].append((inputValue, outputValue))<EOL><DEDENT><DEDENT>self.warpDict = warpDict<EOL> | 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.attrib.get("<STR_LIT>"))<EOL>axis['<STR_LIT:default>'] = float(axisElement.attrib.get("<STR_LIT:default>"))<EOL>axis['<STR_LIT>'] = []<EOL>for warpPoint in axisElement.findall("<STR_LIT>"):<EOL><INDENT>inputValue = float(warpPoint.attrib.get("<STR_LIT:input>"))<EOL>outputValue = float(warpPoint.attrib.get("<STR_LIT>"))<EOL>axis['<STR_LIT>'].append((inputValue, outputValue))<EOL><DEDENT>self.axes[name] = axis<EOL>self.axesOrder.append(axis['<STR_LIT:name>'])<EOL><DEDENT> | 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:<EOL><INDENT>sourceName = "<STR_LIT>"%(sourceCount)<EOL><DEDENT>self.reportProgress("<STR_LIT>", '<STR_LIT>', sourcePath)<EOL>if not os.path.exists(sourcePath):<EOL><INDENT>raise MutatorError("<STR_LIT>"%sourcePath)<EOL><DEDENT>sourceObject = self._instantiateFont(sourcePath)<EOL>sourceLocationObject = None<EOL>sourceLocationObject = self.locationFromElement(sourceElement)<EOL>if sourceLocationObject is None:<EOL><INDENT>raise MutatorError("<STR_LIT>"%sourceName)<EOL><DEDENT>for libElement in sourceElement.findall('<STR_LIT>'):<EOL><INDENT>if libElement.attrib.get('<STR_LIT>') == '<STR_LIT:1>':<EOL><INDENT>self.libSource = sourceName<EOL><DEDENT><DEDENT>for groupsElement in sourceElement.findall('<STR_LIT>'):<EOL><INDENT>if groupsElement.attrib.get('<STR_LIT>') == '<STR_LIT:1>':<EOL><INDENT>self.groupsSource = sourceName<EOL><DEDENT><DEDENT>for infoElement in sourceElement.findall("<STR_LIT>"):<EOL><INDENT>if infoElement.attrib.get('<STR_LIT>') == '<STR_LIT:1>':<EOL><INDENT>self.infoSource = sourceName<EOL><DEDENT>if infoElement.attrib.get('<STR_LIT>') == '<STR_LIT:1>':<EOL><INDENT>self.muted['<STR_LIT:info>'].append(sourceName)<EOL><DEDENT><DEDENT>for featuresElement in sourceElement.findall("<STR_LIT>"):<EOL><INDENT>if featuresElement.attrib.get('<STR_LIT>') == '<STR_LIT:1>':<EOL><INDENT>if self.featuresSource is not None:<EOL><INDENT>self.featuresSource = None<EOL><DEDENT>else:<EOL><INDENT>self.featuresSource = sourceName<EOL><DEDENT><DEDENT><DEDENT>mutedGlyphs = []<EOL>for glyphElement in sourceElement.findall("<STR_LIT>"):<EOL><INDENT>glyphName = glyphElement.attrib.get('<STR_LIT:name>')<EOL>if glyphName is None:<EOL><INDENT>continue<EOL><DEDENT>if glyphElement.attrib.get('<STR_LIT>') == '<STR_LIT:1>':<EOL><INDENT>if not sourceName in self.muted['<STR_LIT>']:<EOL><INDENT>self.muted['<STR_LIT>'][sourceName] = []<EOL><DEDENT>self.muted['<STR_LIT>'][sourceName].append(glyphName)<EOL><DEDENT><DEDENT>for kerningElement in sourceElement.findall("<STR_LIT>"):<EOL><INDENT>if kerningElement.attrib.get('<STR_LIT>') == '<STR_LIT:1>':<EOL><INDENT>self.muted['<STR_LIT>'].append(sourceName)<EOL><DEDENT><DEDENT>self.sources[sourceName] = sourceObject, sourceLocationObject<EOL>self.reportProgress("<STR_LIT>", '<STR_LIT>')<EOL><DEDENT> | 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>if self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>", xValue)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>yValue = dimensionElement.attrib.get('<STR_LIT>')<EOL>if yValue is not None:<EOL><INDENT>yValue = float(yValue)<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>if yValue is not None:<EOL><INDENT>loc[dimName] = (xValue, yValue)<EOL><DEDENT>else:<EOL><INDENT>loc[dimName] = xValue<EOL><DEDENT><DEDENT>return loc<EOL> | 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("<STR_LIT>" % key)<EOL> | 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><DEDENT>filenameTokenForResults = os.path.basename(filename)<EOL>instanceObject = self._instanceWriterClass(instancePath,<EOL>ufoVersion=self.ufoVersion,<EOL>roundGeometry=self.roundGeometry,<EOL>axes = self.axes,<EOL>verbose=self.verbose,<EOL>logger=self.logger<EOL>)<EOL>self.results[filenameTokenForResults] = instancePath<EOL>instanceObject.setSources(self.sources)<EOL>self.unicodeMap = instanceObject.makeUnicodeMapFromSources()<EOL>instanceObject.setMuted(self.muted)<EOL>familyname = instanceElement.attrib.get('<STR_LIT>')<EOL>if familyname is not None:<EOL><INDENT>instanceObject.setFamilyName(familyname)<EOL><DEDENT>stylename = instanceElement.attrib.get('<STR_LIT>')<EOL>if stylename is not None:<EOL><INDENT>instanceObject.setStyleName(stylename)<EOL><DEDENT>postScriptFontName = instanceElement.attrib.get('<STR_LIT>')<EOL>if postScriptFontName is not None:<EOL><INDENT>instanceObject.setPostScriptFontName(postScriptFontName)<EOL><DEDENT>styleMapFamilyName = instanceElement.attrib.get('<STR_LIT>')<EOL>if styleMapFamilyName is not None:<EOL><INDENT>instanceObject.setStyleMapFamilyName(styleMapFamilyName)<EOL><DEDENT>styleMapStyleName = instanceElement.attrib.get('<STR_LIT>')<EOL>if styleMapStyleName is not None:<EOL><INDENT>instanceObject.setStyleMapStyleName(styleMapStyleName)<EOL><DEDENT>instanceLocation = self.locationFromElement(instanceElement)<EOL>if instanceLocation is not None:<EOL><INDENT>instanceObject.setLocation(instanceLocation)<EOL><DEDENT>if makeGlyphs:<EOL><INDENT>names = instanceObject.getAvailableGlyphnames()<EOL>for n in names:<EOL><INDENT>unicodes = self.unicodeMap.get(n, None)<EOL>try:<EOL><INDENT>instanceObject.addGlyph(n, unicodes)<EOL><DEDENT>except AssertionError:<EOL><INDENT>if self.verbose and self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>", n)<EOL><DEDENT><DEDENT><DEDENT>for glyphElement in instanceElement.findall('<STR_LIT>'):<EOL><INDENT>self.readGlyphElement(glyphElement, instanceObject)<EOL><DEDENT><DEDENT>if makeKerning:<EOL><INDENT>for kerningElement in instanceElement.findall('<STR_LIT>'):<EOL><INDENT>self.readKerningElement(kerningElement, instanceObject)<EOL>break<EOL><DEDENT><DEDENT>if makeInfo:<EOL><INDENT>for infoElement in instanceElement.findall('<STR_LIT>'):<EOL><INDENT>self.readInfoElement(infoElement, instanceObject)<EOL><DEDENT><DEDENT>if self.featuresSource is not None:<EOL><INDENT>instanceObject.copyFeatures(self.featuresSource)<EOL><DEDENT>if self.groupsSource is not None:<EOL><INDENT>if self.groupsSource in self.sources:<EOL><INDENT>groupSourceObject, loc = self.sources[self.groupsSource]<EOL>if hasattr(groupSourceObject, "<STR_LIT>"):<EOL><INDENT>renameMap = groupSourceObject.kerningGroupConversionRenameMaps<EOL><DEDENT>else:<EOL><INDENT>renameMap = {}<EOL><DEDENT>instanceObject.setGroups(groupSourceObject.groups, kerningGroupConversionRenameMaps=renameMap)<EOL><DEDENT><DEDENT>if self.libSource is not None:<EOL><INDENT>if self.libSource in self.sources:<EOL><INDENT>libSourceObject, loc = self.sources[self.libSource]<EOL>instanceObject.setLib(libSourceObject.lib)<EOL><DEDENT><DEDENT>success, report = instanceObject.save()<EOL>if not success and self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>", filename, report)<EOL><DEDENT>failed = instanceObject.getFailed()<EOL>if failed:<EOL><INDENT>failed.sort()<EOL>msg = "<STR_LIT>"%(filename, len(failed),"<STR_LIT:\t>"+"<STR_LIT>".join(failed))<EOL>self.reportProgress('<STR_LIT:error>', '<STR_LIT>', msg)<EOL>if self.verbose and self.logger:<EOL><INDENT>self.logger.info(msg)<EOL><DEDENT><DEDENT>missing = instanceObject.getMissingUnicodes()<EOL>if missing:<EOL><INDENT>missing.sort()<EOL>msg = "<STR_LIT>"%(filename, len(missing),"<STR_LIT:\t>"+"<STR_LIT>".join(missing))<EOL>self.reportProgress('<STR_LIT:error>', '<STR_LIT>', msg)<EOL><DEDENT>self.instances[postScriptFontName] = instanceObject<EOL>self.reportProgress("<STR_LIT>", '<STR_LIT>', filenameTokenForResults)<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('<STR_LIT>')<EOL>if unicodes == None:<EOL><INDENT>unicodes = self.unicodeMap.get(glyphName, None)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>unicodes = [int(u, <NUM_LIT:16>) for u in unicodes.split("<STR_LIT:U+0020>")]<EOL><DEDENT>except ValueError:<EOL><INDENT>raise MutatorError("<STR_LIT>" % unicodes)<EOL><DEDENT><DEDENT>note = None<EOL>for noteElement in glyphElement.findall('<STR_LIT>'):<EOL><INDENT>note = noteElement.text<EOL>break<EOL><DEDENT>instanceLocation = self.locationFromElement(glyphElement)<EOL>glyphSources = None<EOL>for masterElement in glyphElement.findall('<STR_LIT>'):<EOL><INDENT>fontSourceName = masterElement.attrib.get('<STR_LIT:source>')<EOL>fontSource, fontLocation = self.sources.get(fontSourceName)<EOL>if fontSource is None:<EOL><INDENT>raise MutatorError("<STR_LIT>"%masterElement)<EOL><DEDENT>sourceLocation = self.locationFromElement(masterElement)<EOL>if sourceLocation is None:<EOL><INDENT>sourceLocation = fontLocation<EOL><DEDENT>masterGlyphName = masterElement.attrib.get('<STR_LIT>')<EOL>if masterGlyphName is None:<EOL><INDENT>masterGlyphName = glyphName<EOL><DEDENT>d = dict( font=fontSource,<EOL>location=sourceLocation,<EOL>glyphName=masterGlyphName)<EOL>if glyphSources is None:<EOL><INDENT>glyphSources = []<EOL><DEDENT>glyphSources.append(d)<EOL><DEDENT>instanceObject.addGlyph(glyphName, unicodes, instanceLocation, glyphSources, note=note)<EOL> | 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 instance from an anisotropic interpolation.
</note>
</glyph> | 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._glyphPointClass,<EOL>glyphComponentClass=self._glyphComponentClass,<EOL>glyphAnchorClass=self._glyphAnchorClass)<EOL> | 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 = DesignSpaceDocumentReader(<EOL>path,<EOL>ufoVersion=outputUFOFormatVersion,<EOL>roundGeometry=roundGeometry,<EOL>verbose=verbose,<EOL>logPath=logPath,<EOL>progressFunc=progressFunc<EOL>)<EOL>reader.process()<EOL>results.append(reader.results)<EOL><DEDENT>reader = None<EOL>return results<EOL> | 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:<EOL><INDENT>if self.verbose and self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>", "<STR_LIT:U+002CU+0020>".join(skipping))<EOL><DEDENT><DEDENT>if kerningGroupConversionRenameMaps:<EOL><INDENT>self.font.kerningGroupConversionRenameMaps = kerningGroupConversionRenameMaps<EOL><DEDENT> | 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><DEDENT><DEDENT> | 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><EOL><DEDENT><DEDENT><DEDENT>for name, u in values.items():<EOL><INDENT>if len(u) == <NUM_LIT:0>:<EOL><INDENT>if "<STR_LIT:.>" not in name:<EOL><INDENT>self._missingUnicodes.append(name)<EOL><DEDENT>continue<EOL><DEDENT>k = list(u.keys())<EOL>self.unicodeValues[name] = k<EOL><DEDENT>return self.unicodeValues<EOL> | 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.
If only a single master has a value, that 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 self.muted['<STR_LIT:info>']:<EOL><INDENT>continue<EOL><DEDENT>items.append((sourceLocation, MathInfo(source.info)))<EOL><DEDENT>try:<EOL><INDENT>bias, m = buildMutator(items, axes=self.axes)<EOL><DEDENT>except:<EOL><INDENT>if self.logger:<EOL><INDENT>self.logger.exception("<STR_LIT>", items)<EOL><DEDENT>return<EOL><DEDENT>instanceObject = m.makeInstance(instanceLocation)<EOL>if self.roundGeometry:<EOL><INDENT>try:<EOL><INDENT>instanceObject = instanceObject.round()<EOL><DEDENT>except AttributeError:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT><DEDENT>instanceObject.extractInfo(self.font.info)<EOL>if copySourceName is not None:<EOL><INDENT>if not copySourceName in sources:<EOL><INDENT>if self.verbose and self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>", copySourceName)<EOL>return<EOL><DEDENT><DEDENT>copySourceObject, loc = sources[copySourceName]<EOL>self._copyFontInfo(self.font.info, copySourceObject.info)<EOL><DEDENT> | 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_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_LIT>"<EOL>]<EOL>for infoAttribute in infoAttributes:<EOL><INDENT>copy = False<EOL>if self.ufoVersion == <NUM_LIT:1> and infoAttribute in fontInfoAttributesVersion1:<EOL><INDENT>copy = True<EOL><DEDENT>elif self.ufoVersion == <NUM_LIT:2> and infoAttribute in fontInfoAttributesVersion2:<EOL><INDENT>copy = True<EOL><DEDENT>elif self.ufoVersion == <NUM_LIT:3> and infoAttribute in fontInfoAttributesVersion3:<EOL><INDENT>copy = True<EOL><DEDENT>if copy:<EOL><INDENT>value = getattr(sourceInfo, infoAttribute)<EOL>setattr(targetInfo, infoAttribute, value)<EOL><DEDENT><DEDENT> | 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 sourceName in self.muted['<STR_LIT>']:<EOL><INDENT>if self.verbose and self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>", instanceLocation)<EOL><DEDENT>continue<EOL><DEDENT>if len(source.kerning.keys())><NUM_LIT:0>:<EOL><INDENT>items.append((sourceLocation, MathKerning(source.kerning, source.groups)))<EOL><DEDENT><DEDENT>if items:<EOL><INDENT>m = None<EOL>try:<EOL><INDENT>bias, m = buildMutator(items, axes=self.axes)<EOL><DEDENT>except:<EOL><INDENT>if self.logger:<EOL><INDENT>self.logger.exception("<STR_LIT>", items)<EOL><DEDENT>return<EOL><DEDENT>instanceObject = m.makeInstance(instanceLocation)<EOL>if self.roundGeometry:<EOL><INDENT>instanceObject.round()<EOL><DEDENT>instanceObject.extractKerning(self.font)<EOL><DEDENT> | 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>glyphMasters = []<EOL>if sources is None:<EOL><INDENT>for sourceName, (source, sourceLocation) in self.sources.items():<EOL><INDENT>if glyphName in self.muted['<STR_LIT>'].get(sourceName, []):<EOL><INDENT>continue<EOL><DEDENT>d = dict( font=source,<EOL>location=sourceLocation,<EOL>glyphName=glyphName)<EOL>glyphMasters.append(d)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>glyphMasters = sources<EOL><DEDENT>try:<EOL><INDENT>self._calculateGlyph(glyphObject, instanceLocation, glyphMasters)<EOL><DEDENT>except:<EOL><INDENT>self._failed.append(glyphName)<EOL><DEDENT> | 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((locationObject, glyphObject))<EOL><DEDENT>bias, m = buildMutator(items, axes=self.axes)<EOL>instanceObject = m.makeInstance(instanceLocationObject)<EOL>if self.roundGeometry:<EOL><INDENT>try:<EOL><INDENT>instanceObject = instanceObject.round()<EOL><DEDENT>except AttributeError:<EOL><INDENT>if self.verbose and self.logger:<EOL><INDENT>self.logger.info("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>try:<EOL><INDENT>instanceObject.extractGlyph(targetGlyphObject, onlyGeometry=True)<EOL><DEDENT>except TypeError:<EOL><INDENT>pPen = targetGlyphObject.getPointPen()<EOL>targetGlyphObject.clear()<EOL>instanceObject.drawPoints(pPen)<EOL>targetGlyphObject.width = instanceObject.width<EOL><DEDENT> | 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>os.makedirs(directory)<EOL><DEDENT>try:<EOL><INDENT>self.font.save(os.path.abspath(self.path), self.ufoVersion)<EOL><DEDENT>except defcon.DefconError as error:<EOL><INDENT>if self.logger:<EOL><INDENT>self.logger.exception("<STR_LIT>")<EOL><DEDENT>return False, error.report<EOL><DEDENT>return True, None<EOL> | 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>return meta_wrapper<EOL> | 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(request)
... pass
>>> my_view.urljects_view = True
>>> my_view.url = U / 'my_view'
>>> my_view.url_name = 'my_view'
Those view are then supposed to be used with ``view_include`` which will
register all views that have ``urljects_view`` set to ``True``.
:param url_pattern: regex or URLPattern or anything passable to url()
:param name: name of the view, __name__ will be used otherwise.
:param priority: priority of the view, the lower the better | 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><DEDENT>return urls.url(<EOL>regex=url_pattern,<EOL>view=view,<EOL>kwargs=kwargs,<EOL>name=name)<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
:param kwargs: kwargs that are to be passed to view
:param name: name of the view, if empty it will be guessed | 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 = (inspect.isfunction(member) and<EOL>hasattr(member, '<STR_LIT>') and<EOL>member.urljects_view)<EOL>if (is_class_view and member is not URLView) or is_func_view:<EOL><INDENT>view_dict[member.url_priority].append(<EOL>url(member.url, member, name=member.url_name))<EOL><DEDENT><DEDENT>view_patterns = list(*[<EOL>view_dict[priority] for priority in sorted(view_dict)<EOL>])<EOL>return urls.include(<EOL>arg=view_patterns,<EOL>namespace=namespace,<EOL>app_name=app_name)<EOL> | 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, it will be guessed otherwise
:param app_name: application name
:return: result of urls.include | 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 view is not None:<EOL><INDENT>return router_decorator(view)<EOL><DEDENT>return router_decorator<EOL> | 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_name() will be used otherwise.
:param priority: priority for sorting; pass e.g. -1 for catch-all route
:param kwargs: passed to url() | 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[i] = t.year*<NUM_LIT:1000> + int(t.strftime('<STR_LIT>'))<EOL><DEDENT>return yd.squeeze()[()], utsec.squeeze()[()]<EOL> | 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><DEDENT>yeardate = int(yeardate)<EOL>yd = str(yeardate)<EOL>if len(yd) != <NUM_LIT:7>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>year = int(yd[:<NUM_LIT:4>])<EOL>assert <NUM_LIT:0> < year < <NUM_LIT>, '<STR_LIT>'<EOL>dt = datetime.datetime(year, <NUM_LIT:1>, <NUM_LIT:1>) + datetime.timedelta(days=int(yd[<NUM_LIT:4>:]) - <NUM_LIT:1>)<EOL>assert isinstance(dt, datetime.datetime)<EOL>if utsec is not None:<EOL><INDENT>dt += datetime.timedelta(seconds=utsec)<EOL><DEDENT>return dt<EOL> | 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(), '<STR_LIT>'<EOL>return doy, year<EOL> | < 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><INDENT>t = t.astype(datetime.datetime)<EOL><DEDENT>elif isinstance(t, (datetime.datetime, datetime.date)):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(type(t)))<EOL><DEDENT>doy[i] = int(t.strftime('<STR_LIT>'))<EOL>utsec[i] = datetime2utsec(t)<EOL>stl[i, ...] = utsec[i] / <NUM_LIT> + glon / <NUM_LIT><EOL><DEDENT>return doy, utsec, stl<EOL><DEDENT> | 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)<EOL><DEDENT>elif isinstance(t, str):<EOL><INDENT>t = parse(t)<EOL><DEDENT>return datetime.timedelta.total_seconds(t - datetime.datetime.combine(t.date(),<EOL>datetime.datetime.min.time()))<EOL> | 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.timedelta(seconds=seconds)<EOL>assert isinstance(T, datetime.datetime)<EOL><DEDENT>elif isinstance(atime[<NUM_LIT:0>], float):<EOL><INDENT>return np.asarray([yeardec2datetime(t) for t in atime])<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(type(atime)))<EOL><DEDENT>return T<EOL><DEDENT> | 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) to datetime,
and from datetime to decimal year. | 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)):<EOL><INDENT>return np.asarray([datetime2yeardec(t) for t in time])<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(type(time)))<EOL><DEDENT>year = t.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>return year + ((t - boy).total_seconds() / ((eoy - boy).total_seconds()))<EOL> | 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=<NUM_LIT:20>):<EOL><INDENT>return MinuteLocator(byminute=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:5>)), MinuteLocator(byminute=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:2>))<EOL><DEDENT>elif (timedelta(minutes=<NUM_LIT:10>) < tdiff) & (tdiff <= timedelta(minutes=<NUM_LIT:20>)):<EOL><INDENT>return MinuteLocator(byminute=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:2>)), MinuteLocator(byminute=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:1>))<EOL><DEDENT>elif (timedelta(minutes=<NUM_LIT:5>) < tdiff) & (tdiff <= timedelta(minutes=<NUM_LIT:10>)):<EOL><INDENT>return MinuteLocator(byminute=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:1>)), SecondLocator(bysecond=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:30>))<EOL><DEDENT>elif (timedelta(minutes=<NUM_LIT:1>) < tdiff) & (tdiff <= timedelta(minutes=<NUM_LIT:5>)):<EOL><INDENT>return SecondLocator(bysecond=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:30>)), SecondLocator(bysecond=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:10>))<EOL><DEDENT>elif (timedelta(seconds=<NUM_LIT:30>) < tdiff) & (tdiff <= timedelta(minutes=<NUM_LIT:1>)):<EOL><INDENT>return SecondLocator(bysecond=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:10>)), SecondLocator(bysecond=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:2>))<EOL><DEDENT>else:<EOL><INDENT>return SecondLocator(bysecond=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:2>)), SecondLocator(bysecond=range(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:1>))<EOL><DEDENT> | 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 t<EOL><DEDENT>elif isinstance(t, (np.ndarray, list, tuple)):<EOL><INDENT>return np.asarray([forceutc(T) for T in t])<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL> | 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 enumerate(x0):<EOL><INDENT>if xi is not None and (isinstance(xi, (datetime.datetime, datetime.date, np.datetime64)) or np.isfinite(xi)):<EOL><INDENT>ind[i] = np.nanargmin(abs(x-xi))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>return ind.squeeze()[()], x[ind].squeeze()[()]<EOL> | 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 bisect.bisect() gives the incorrect result!
idea based on:
http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array | 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>': req.json()['<STR_LIT:result>'], '<STR_LIT:user>': user, '<STR_LIT:url>': url}<EOL> | 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<EOL>text += '<STR_LIT>'<EOL>text += '<STR_LIT>'.format('<STR_LIT:U+002CU+0020>'.join(task.variables))<EOL>yield events.help_output(text)<EOL> | 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 in args)<EOL>}<EOL> | 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 isinstance(obj, (Event, Task, Variable, Step)):<EOL><INDENT>return self.serialise(obj._asdict())<EOL><DEDENT>elif obj is None:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(type(obj))<EOL><DEDENT> | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.